three.webgpu.nodes.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386
  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 member type for the given name.
  1024. *
  1025. * @param {NodeBuilder} builder - The current node builder.
  1026. * @param {String} name - The name of the member.
  1027. * @return {String} The type of the node.
  1028. */
  1029. getMemberType( /*uilder, name*/ ) {
  1030. return 'void';
  1031. }
  1032. /**
  1033. * Returns the node's type.
  1034. *
  1035. * @param {NodeBuilder} builder - The current node builder.
  1036. * @return {String} The type of the node.
  1037. */
  1038. getNodeType( builder ) {
  1039. const nodeProperties = builder.getNodeProperties( this );
  1040. if ( nodeProperties.outputNode ) {
  1041. return nodeProperties.outputNode.getNodeType( builder );
  1042. }
  1043. return this.nodeType;
  1044. }
  1045. /**
  1046. * This method is used during the build process of a node and ensures
  1047. * equal nodes are not built multiple times but just once. For example if
  1048. * `attribute( 'uv' )` is used multiple times by the user, the build
  1049. * process makes sure to process just the first node.
  1050. *
  1051. * @param {NodeBuilder} builder - The current node builder.
  1052. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1053. */
  1054. getShared( builder ) {
  1055. const hash = this.getHash( builder );
  1056. const nodeFromHash = builder.getNodeFromHash( hash );
  1057. return nodeFromHash || this;
  1058. }
  1059. /**
  1060. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1061. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1062. * The output node must be returned in the `return` statement.
  1063. *
  1064. * @param {NodeBuilder} builder - The current node builder.
  1065. * @return {Node?} The output node.
  1066. */
  1067. setup( builder ) {
  1068. const nodeProperties = builder.getNodeProperties( this );
  1069. let index = 0;
  1070. for ( const childNode of this.getChildren() ) {
  1071. nodeProperties[ 'node' + index ++ ] = childNode;
  1072. }
  1073. // return a outputNode if exists or null
  1074. return nodeProperties.outputNode || null;
  1075. }
  1076. /**
  1077. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1078. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1079. *
  1080. * @param {NodeBuilder} builder - The current node builder.
  1081. */
  1082. analyze( builder ) {
  1083. const usageCount = builder.increaseUsage( this );
  1084. if ( usageCount === 1 ) {
  1085. // node flow children
  1086. const nodeProperties = builder.getNodeProperties( this );
  1087. for ( const childNode of Object.values( nodeProperties ) ) {
  1088. if ( childNode && childNode.isNode === true ) {
  1089. childNode.build( builder );
  1090. }
  1091. }
  1092. }
  1093. }
  1094. /**
  1095. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1096. * This state builds the output node and returns the resulting shader string.
  1097. *
  1098. * @param {NodeBuilder} builder - The current node builder.
  1099. * @param {String?} output - Can be used to define the output type.
  1100. * @return {String?} The generated shader string.
  1101. */
  1102. generate( builder, output ) {
  1103. const { outputNode } = builder.getNodeProperties( this );
  1104. if ( outputNode && outputNode.isNode === true ) {
  1105. return outputNode.build( builder, output );
  1106. }
  1107. }
  1108. /**
  1109. * The method can be implemented to update the node's internal state before it is used to render an object.
  1110. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1111. *
  1112. * @abstract
  1113. * @param {NodeFrame} frame - A reference to the current node frame.
  1114. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1115. */
  1116. updateBefore( /*frame*/ ) {
  1117. console.warn( 'Abstract function.' );
  1118. }
  1119. /**
  1120. * The method can be implemented to update the node's internal state after it was used to render an object.
  1121. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1122. *
  1123. * @abstract
  1124. * @param {NodeFrame} frame - A reference to the current node frame.
  1125. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1126. */
  1127. updateAfter( /*frame*/ ) {
  1128. console.warn( 'Abstract function.' );
  1129. }
  1130. /**
  1131. * The method can be implemented to update the node's internal state when it is used to render an object.
  1132. * The {@link Node#updateType} property defines how often the update is executed.
  1133. *
  1134. * @abstract
  1135. * @param {NodeFrame} frame - A reference to the current node frame.
  1136. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1137. */
  1138. update( /*frame*/ ) {
  1139. console.warn( 'Abstract function.' );
  1140. }
  1141. /**
  1142. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1143. * on the current build stage (setup, analyze or generate).
  1144. *
  1145. * @param {NodeBuilder} builder - The current node builder.
  1146. * @param {String?} output - Can be used to define the output type.
  1147. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1148. */
  1149. build( builder, output = null ) {
  1150. const refNode = this.getShared( builder );
  1151. if ( this !== refNode ) {
  1152. return refNode.build( builder, output );
  1153. }
  1154. builder.addNode( this );
  1155. builder.addChain( this );
  1156. /* Build stages expected results:
  1157. - "setup" -> Node
  1158. - "analyze" -> null
  1159. - "generate" -> String
  1160. */
  1161. let result = null;
  1162. const buildStage = builder.getBuildStage();
  1163. if ( buildStage === 'setup' ) {
  1164. this.updateReference( builder );
  1165. const properties = builder.getNodeProperties( this );
  1166. if ( properties.initialized !== true ) {
  1167. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1168. properties.initialized = true;
  1169. const outputNode = this.setup( builder ); // return a node or null
  1170. const isNodeOutput = outputNode && outputNode.isNode === true;
  1171. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1172. // !! no outputNode !!
  1173. //outputNode = builder.stack;
  1174. }*/
  1175. for ( const childNode of Object.values( properties ) ) {
  1176. if ( childNode && childNode.isNode === true ) {
  1177. childNode.build( builder );
  1178. }
  1179. }
  1180. if ( isNodeOutput ) {
  1181. outputNode.build( builder );
  1182. }
  1183. properties.outputNode = outputNode;
  1184. }
  1185. } else if ( buildStage === 'analyze' ) {
  1186. this.analyze( builder );
  1187. } else if ( buildStage === 'generate' ) {
  1188. const isGenerateOnce = this.generate.length === 1;
  1189. if ( isGenerateOnce ) {
  1190. const type = this.getNodeType( builder );
  1191. const nodeData = builder.getDataFromNode( this );
  1192. result = nodeData.snippet;
  1193. if ( result === undefined ) {
  1194. result = this.generate( builder ) || '';
  1195. nodeData.snippet = result;
  1196. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1197. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1198. }
  1199. result = builder.format( result, type, output );
  1200. } else {
  1201. result = this.generate( builder, output ) || '';
  1202. }
  1203. }
  1204. builder.removeChain( this );
  1205. builder.addSequentialNode( this );
  1206. return result;
  1207. }
  1208. /**
  1209. * Returns the child nodes as a JSON object.
  1210. *
  1211. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1212. */
  1213. getSerializeChildren() {
  1214. return getNodeChildren( this );
  1215. }
  1216. /**
  1217. * Serializes the node to JSON.
  1218. *
  1219. * @param {Object} json - The output JSON object.
  1220. */
  1221. serialize( json ) {
  1222. const nodeChildren = this.getSerializeChildren();
  1223. const inputNodes = {};
  1224. for ( const { property, index, childNode } of nodeChildren ) {
  1225. if ( index !== undefined ) {
  1226. if ( inputNodes[ property ] === undefined ) {
  1227. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1228. }
  1229. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1230. } else {
  1231. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1232. }
  1233. }
  1234. if ( Object.keys( inputNodes ).length > 0 ) {
  1235. json.inputNodes = inputNodes;
  1236. }
  1237. }
  1238. /**
  1239. * Deserializes the node from the given JSON.
  1240. *
  1241. * @param {Object} json - The JSON object.
  1242. */
  1243. deserialize( json ) {
  1244. if ( json.inputNodes !== undefined ) {
  1245. const nodes = json.meta.nodes;
  1246. for ( const property in json.inputNodes ) {
  1247. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1248. const inputArray = [];
  1249. for ( const uuid of json.inputNodes[ property ] ) {
  1250. inputArray.push( nodes[ uuid ] );
  1251. }
  1252. this[ property ] = inputArray;
  1253. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1254. const inputObject = {};
  1255. for ( const subProperty in json.inputNodes[ property ] ) {
  1256. const uuid = json.inputNodes[ property ][ subProperty ];
  1257. inputObject[ subProperty ] = nodes[ uuid ];
  1258. }
  1259. this[ property ] = inputObject;
  1260. } else {
  1261. const uuid = json.inputNodes[ property ];
  1262. this[ property ] = nodes[ uuid ];
  1263. }
  1264. }
  1265. }
  1266. }
  1267. /**
  1268. * Serializes the node into the three.js JSON Object/Scene format.
  1269. *
  1270. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1271. * @return {Object} The serialized node.
  1272. */
  1273. toJSON( meta ) {
  1274. const { uuid, type } = this;
  1275. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1276. if ( isRoot ) {
  1277. meta = {
  1278. textures: {},
  1279. images: {},
  1280. nodes: {}
  1281. };
  1282. }
  1283. // serialize
  1284. let data = meta.nodes[ uuid ];
  1285. if ( data === undefined ) {
  1286. data = {
  1287. uuid,
  1288. type,
  1289. meta,
  1290. metadata: {
  1291. version: 4.6,
  1292. type: 'Node',
  1293. generator: 'Node.toJSON'
  1294. }
  1295. };
  1296. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1297. this.serialize( data );
  1298. delete data.meta;
  1299. }
  1300. // TODO: Copied from Object3D.toJSON
  1301. function extractFromCache( cache ) {
  1302. const values = [];
  1303. for ( const key in cache ) {
  1304. const data = cache[ key ];
  1305. delete data.metadata;
  1306. values.push( data );
  1307. }
  1308. return values;
  1309. }
  1310. if ( isRoot ) {
  1311. const textures = extractFromCache( meta.textures );
  1312. const images = extractFromCache( meta.images );
  1313. const nodes = extractFromCache( meta.nodes );
  1314. if ( textures.length > 0 ) data.textures = textures;
  1315. if ( images.length > 0 ) data.images = images;
  1316. if ( nodes.length > 0 ) data.nodes = nodes;
  1317. }
  1318. return data;
  1319. }
  1320. }
  1321. /**
  1322. * Base class for representing element access on an array-like
  1323. * node data structures.
  1324. *
  1325. * @augments Node
  1326. */
  1327. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1328. static get type() {
  1329. return 'ArrayElementNode';
  1330. }
  1331. /**
  1332. * Constructs an array element node.
  1333. *
  1334. * @param {Node} node - The array-like node.
  1335. * @param {Node} indexNode - The index node that defines the element access.
  1336. */
  1337. constructor( node, indexNode ) {
  1338. super();
  1339. /**
  1340. * The array-like node.
  1341. *
  1342. * @type {Node}
  1343. */
  1344. this.node = node;
  1345. /**
  1346. * The index node that defines the element access.
  1347. *
  1348. * @type {Node}
  1349. */
  1350. this.indexNode = indexNode;
  1351. /**
  1352. * This flag can be used for type testing.
  1353. *
  1354. * @type {Boolean}
  1355. * @readonly
  1356. * @default true
  1357. */
  1358. this.isArrayElementNode = true;
  1359. }
  1360. /**
  1361. * This method is overwritten since the node type is inferred from the array-like node.
  1362. *
  1363. * @param {NodeBuilder} builder - The current node builder.
  1364. * @return {String} The node type.
  1365. */
  1366. getNodeType( builder ) {
  1367. return this.node.getElementType( builder );
  1368. }
  1369. generate( builder ) {
  1370. const nodeSnippet = this.node.build( builder );
  1371. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1372. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1373. }
  1374. }
  1375. /**
  1376. * This module is part of the TSL core and usually not used in app level code.
  1377. * It represents a convert operation during the shader generation process
  1378. * meaning it converts the data type of a node to a target data type.
  1379. *
  1380. * @augments Node
  1381. */
  1382. class ConvertNode extends Node {
  1383. static get type() {
  1384. return 'ConvertNode';
  1385. }
  1386. /**
  1387. * Constructs a new convert node.
  1388. *
  1389. * @param {Node} node - The node which type should be converted.
  1390. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1391. */
  1392. constructor( node, convertTo ) {
  1393. super();
  1394. /**
  1395. * The node which type should be converted.
  1396. *
  1397. * @type {Node}
  1398. */
  1399. this.node = node;
  1400. /**
  1401. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1402. *
  1403. * @type {String}
  1404. */
  1405. this.convertTo = convertTo;
  1406. }
  1407. /**
  1408. * This method is overwritten since the implementation tries to infer the best
  1409. * matching type from the {@link ConvertNode#convertTo} property.
  1410. *
  1411. * @param {NodeBuilder} builder - The current node builder.
  1412. * @return {String} The node type.
  1413. */
  1414. getNodeType( builder ) {
  1415. const requestType = this.node.getNodeType( builder );
  1416. let convertTo = null;
  1417. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1418. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1419. convertTo = overloadingType;
  1420. }
  1421. }
  1422. return convertTo;
  1423. }
  1424. serialize( data ) {
  1425. super.serialize( data );
  1426. data.convertTo = this.convertTo;
  1427. }
  1428. deserialize( data ) {
  1429. super.deserialize( data );
  1430. this.convertTo = data.convertTo;
  1431. }
  1432. generate( builder, output ) {
  1433. const node = this.node;
  1434. const type = this.getNodeType( builder );
  1435. const snippet = node.build( builder, type );
  1436. return builder.format( snippet, type, output );
  1437. }
  1438. }
  1439. /**
  1440. * This module uses cache management to create temporary variables
  1441. * if the node is used more than once to prevent duplicate calculations.
  1442. *
  1443. * The class acts as a base class for many other nodes types.
  1444. *
  1445. * @augments Node
  1446. */
  1447. class TempNode extends Node {
  1448. static get type() {
  1449. return 'TempNode';
  1450. }
  1451. /**
  1452. * Constructs a temp node.
  1453. *
  1454. * @param {String?} nodeType - The node type.
  1455. */
  1456. constructor( nodeType = null ) {
  1457. super( nodeType );
  1458. /**
  1459. * This flag can be used for type testing.
  1460. *
  1461. * @type {Boolean}
  1462. * @readonly
  1463. * @default true
  1464. */
  1465. this.isTempNode = true;
  1466. }
  1467. /**
  1468. * Whether this node is used more than once in context of other nodes.
  1469. *
  1470. * @param {NodeBuilder} builder - The node builder.
  1471. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1472. */
  1473. hasDependencies( builder ) {
  1474. return builder.getDataFromNode( this ).usageCount > 1;
  1475. }
  1476. build( builder, output ) {
  1477. const buildStage = builder.getBuildStage();
  1478. if ( buildStage === 'generate' ) {
  1479. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1480. const nodeData = builder.getDataFromNode( this );
  1481. if ( nodeData.propertyName !== undefined ) {
  1482. return builder.format( nodeData.propertyName, type, output );
  1483. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1484. const snippet = super.build( builder, type );
  1485. const nodeVar = builder.getVarFromNode( this, null, type );
  1486. const propertyName = builder.getPropertyName( nodeVar );
  1487. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1488. nodeData.snippet = snippet;
  1489. nodeData.propertyName = propertyName;
  1490. return builder.format( nodeData.propertyName, type, output );
  1491. }
  1492. }
  1493. return super.build( builder, output );
  1494. }
  1495. }
  1496. /**
  1497. * This module is part of the TSL core and usually not used in app level code.
  1498. * It represents a join operation during the shader generation process.
  1499. * For example in can compose/join two single floats into a `vec2` type.
  1500. *
  1501. * @augments TempNode
  1502. */
  1503. class JoinNode extends TempNode {
  1504. static get type() {
  1505. return 'JoinNode';
  1506. }
  1507. /**
  1508. * Constructs a new join node.
  1509. *
  1510. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1511. * @param {String?} [nodeType=null] - The node type.
  1512. */
  1513. constructor( nodes = [], nodeType = null ) {
  1514. super( nodeType );
  1515. /**
  1516. * An array of nodes that should be joined.
  1517. *
  1518. * @type {Array<Node>}
  1519. */
  1520. this.nodes = nodes;
  1521. }
  1522. /**
  1523. * This method is overwritten since the node type must be inferred from the
  1524. * joined data length if not explicitly defined.
  1525. *
  1526. * @param {NodeBuilder} builder - The current node builder.
  1527. * @return {String} The node type.
  1528. */
  1529. getNodeType( builder ) {
  1530. if ( this.nodeType !== null ) {
  1531. return builder.getVectorType( this.nodeType );
  1532. }
  1533. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1534. }
  1535. generate( builder, output ) {
  1536. const type = this.getNodeType( builder );
  1537. const nodes = this.nodes;
  1538. const primitiveType = builder.getComponentType( type );
  1539. const snippetValues = [];
  1540. for ( const input of nodes ) {
  1541. let inputSnippet = input.build( builder );
  1542. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1543. if ( inputPrimitiveType !== primitiveType ) {
  1544. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1545. }
  1546. snippetValues.push( inputSnippet );
  1547. }
  1548. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1549. return builder.format( snippet, type, output );
  1550. }
  1551. }
  1552. const _stringVectorComponents = vectorComponents.join( '' );
  1553. /**
  1554. * This module is part of the TSL core and usually not used in app level code.
  1555. * `SplitNode` represents a property access operation which means it is
  1556. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1557. * For example:
  1558. * ```js
  1559. * const redValue = color.r;
  1560. * ```
  1561. *
  1562. * @augments Node
  1563. */
  1564. class SplitNode extends Node {
  1565. static get type() {
  1566. return 'SplitNode';
  1567. }
  1568. /**
  1569. * Constructs a new split node.
  1570. *
  1571. * @param {Node} node - The node that should be accessed.
  1572. * @param {String} [components='x'] - The components that should be accessed.
  1573. */
  1574. constructor( node, components = 'x' ) {
  1575. super();
  1576. /**
  1577. * The node that should be accessed.
  1578. *
  1579. * @type {Node}
  1580. */
  1581. this.node = node;
  1582. /**
  1583. * The components that should be accessed.
  1584. *
  1585. * @type {string}
  1586. */
  1587. this.components = components;
  1588. /**
  1589. * This flag can be used for type testing.
  1590. *
  1591. * @type {Boolean}
  1592. * @readonly
  1593. * @default true
  1594. */
  1595. this.isSplitNode = true;
  1596. }
  1597. /**
  1598. * Returns the vector length which is computed based on the requested components.
  1599. *
  1600. * @return {Number} The vector length.
  1601. */
  1602. getVectorLength() {
  1603. let vectorLength = this.components.length;
  1604. for ( const c of this.components ) {
  1605. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1606. }
  1607. return vectorLength;
  1608. }
  1609. /**
  1610. * Returns the component type of the node's type.
  1611. *
  1612. * @param {NodeBuilder} builder - The current node builder.
  1613. * @return {String} The component type.
  1614. */
  1615. getComponentType( builder ) {
  1616. return builder.getComponentType( this.node.getNodeType( builder ) );
  1617. }
  1618. /**
  1619. * This method is overwritten since the node type is inferred from requested components.
  1620. *
  1621. * @param {NodeBuilder} builder - The current node builder.
  1622. * @return {String} The node type.
  1623. */
  1624. getNodeType( builder ) {
  1625. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1626. }
  1627. generate( builder, output ) {
  1628. const node = this.node;
  1629. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1630. let snippet = null;
  1631. if ( nodeTypeLength > 1 ) {
  1632. let type = null;
  1633. const componentsLength = this.getVectorLength();
  1634. if ( componentsLength >= nodeTypeLength ) {
  1635. // needed expand the input node
  1636. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1637. }
  1638. const nodeSnippet = node.build( builder, type );
  1639. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1640. // unnecessary swizzle
  1641. snippet = builder.format( nodeSnippet, type, output );
  1642. } else {
  1643. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1644. }
  1645. } else {
  1646. // ignore .components if .node returns float/integer
  1647. snippet = node.build( builder, output );
  1648. }
  1649. return snippet;
  1650. }
  1651. serialize( data ) {
  1652. super.serialize( data );
  1653. data.components = this.components;
  1654. }
  1655. deserialize( data ) {
  1656. super.deserialize( data );
  1657. this.components = data.components;
  1658. }
  1659. }
  1660. /**
  1661. * This module is part of the TSL core and usually not used in app level code.
  1662. * `SetNode` represents a set operation which means it is used to implement any
  1663. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1664. * For example:
  1665. * ```js
  1666. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1667. * ```
  1668. *
  1669. * @augments TempNode
  1670. */
  1671. class SetNode extends TempNode {
  1672. static get type() {
  1673. return 'SetNode';
  1674. }
  1675. /**
  1676. * Constructs a new set node.
  1677. *
  1678. * @param {Node} sourceNode - The node that should be updated.
  1679. * @param {String} components - The components that should be updated.
  1680. * @param {Node} targetNode - The value node.
  1681. */
  1682. constructor( sourceNode, components, targetNode ) {
  1683. super();
  1684. /**
  1685. * The node that should be updated.
  1686. *
  1687. * @type {Node}
  1688. */
  1689. this.sourceNode = sourceNode;
  1690. /**
  1691. * The components that should be updated.
  1692. *
  1693. * @type {String}
  1694. */
  1695. this.components = components;
  1696. /**
  1697. * The value node.
  1698. *
  1699. * @type {Node}
  1700. */
  1701. this.targetNode = targetNode;
  1702. }
  1703. /**
  1704. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1705. *
  1706. * @param {NodeBuilder} builder - The current node builder.
  1707. * @return {String} The node type.
  1708. */
  1709. getNodeType( builder ) {
  1710. return this.sourceNode.getNodeType( builder );
  1711. }
  1712. generate( builder ) {
  1713. const { sourceNode, components, targetNode } = this;
  1714. const sourceType = this.getNodeType( builder );
  1715. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1716. const targetType = builder.getTypeFromLength( components.length, componentType );
  1717. const targetSnippet = targetNode.build( builder, targetType );
  1718. const sourceSnippet = sourceNode.build( builder, sourceType );
  1719. const length = builder.getTypeLength( sourceType );
  1720. const snippetValues = [];
  1721. for ( let i = 0; i < length; i ++ ) {
  1722. const component = vectorComponents[ i ];
  1723. if ( component === components[ 0 ] ) {
  1724. snippetValues.push( targetSnippet );
  1725. i += components.length - 1;
  1726. } else {
  1727. snippetValues.push( sourceSnippet + '.' + component );
  1728. }
  1729. }
  1730. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1731. }
  1732. }
  1733. /**
  1734. * This module is part of the TSL core and usually not used in app level code.
  1735. * It represents a flip operation during the shader generation process
  1736. * meaning it flips normalized values with the following formula:
  1737. * ```
  1738. * x = 1 - x;
  1739. * ```
  1740. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1741. * `flipSTPQ()` method invocations on node objects. For example:
  1742. * ```js
  1743. * uvNode = uvNode.flipY();
  1744. * ```
  1745. *
  1746. * @augments TempNode
  1747. */
  1748. class FlipNode extends TempNode {
  1749. static get type() {
  1750. return 'FlipNode';
  1751. }
  1752. /**
  1753. * Constructs a new flip node.
  1754. *
  1755. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1756. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1757. */
  1758. constructor( sourceNode, components ) {
  1759. super();
  1760. /**
  1761. * The node which component(s) should be flipped.
  1762. *
  1763. * @type {Node}
  1764. */
  1765. this.sourceNode = sourceNode;
  1766. /**
  1767. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1768. *
  1769. * @type {String}
  1770. */
  1771. this.components = components;
  1772. }
  1773. /**
  1774. * This method is overwritten since the node type is inferred from the source node.
  1775. *
  1776. * @param {NodeBuilder} builder - The current node builder.
  1777. * @return {String} The node type.
  1778. */
  1779. getNodeType( builder ) {
  1780. return this.sourceNode.getNodeType( builder );
  1781. }
  1782. generate( builder ) {
  1783. const { components, sourceNode } = this;
  1784. const sourceType = this.getNodeType( builder );
  1785. const sourceSnippet = sourceNode.build( builder );
  1786. const sourceCache = builder.getVarFromNode( this );
  1787. const sourceProperty = builder.getPropertyName( sourceCache );
  1788. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1789. const length = builder.getTypeLength( sourceType );
  1790. const snippetValues = [];
  1791. let componentIndex = 0;
  1792. for ( let i = 0; i < length; i ++ ) {
  1793. const component = vectorComponents[ i ];
  1794. if ( component === components[ componentIndex ] ) {
  1795. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1796. componentIndex ++;
  1797. } else {
  1798. snippetValues.push( sourceProperty + '.' + component );
  1799. }
  1800. }
  1801. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1802. }
  1803. }
  1804. /**
  1805. * Base class for representing data input nodes.
  1806. *
  1807. * @augments Node
  1808. */
  1809. class InputNode extends Node {
  1810. static get type() {
  1811. return 'InputNode';
  1812. }
  1813. /**
  1814. * Constructs a new input node.
  1815. *
  1816. * @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).
  1817. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1818. */
  1819. constructor( value, nodeType = null ) {
  1820. super( nodeType );
  1821. /**
  1822. * This flag can be used for type testing.
  1823. *
  1824. * @type {Boolean}
  1825. * @readonly
  1826. * @default true
  1827. */
  1828. this.isInputNode = true;
  1829. /**
  1830. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1831. *
  1832. * @type {Any}
  1833. */
  1834. this.value = value;
  1835. /**
  1836. * The precision of the value in the shader.
  1837. *
  1838. * @type {('low'|'medium'|'high')?}
  1839. * @default null
  1840. */
  1841. this.precision = null;
  1842. }
  1843. getNodeType( /*builder*/ ) {
  1844. if ( this.nodeType === null ) {
  1845. return getValueType( this.value );
  1846. }
  1847. return this.nodeType;
  1848. }
  1849. /**
  1850. * Returns the input type of the node which is by default the node type. Derived modules
  1851. * might overwrite this method and use a fixed type or compute one analytically.
  1852. *
  1853. * A typical example for different input and node types are textures. The input type of a
  1854. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1855. *
  1856. * @param {NodeBuilder} builder - The current node builder.
  1857. * @return {String} The input type.
  1858. */
  1859. getInputType( builder ) {
  1860. return this.getNodeType( builder );
  1861. }
  1862. /**
  1863. * Sets the precision to the given value. The method can be
  1864. * overwritten in derived classes if the final precision must be computed
  1865. * analytically.
  1866. *
  1867. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1868. * @return {InputNode} A reference to this node.
  1869. */
  1870. setPrecision( precision ) {
  1871. this.precision = precision;
  1872. return this;
  1873. }
  1874. serialize( data ) {
  1875. super.serialize( data );
  1876. data.value = this.value;
  1877. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1878. data.valueType = getValueType( this.value );
  1879. data.nodeType = this.nodeType;
  1880. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1881. data.precision = this.precision;
  1882. }
  1883. deserialize( data ) {
  1884. super.deserialize( data );
  1885. this.nodeType = data.nodeType;
  1886. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1887. this.precision = data.precision || null;
  1888. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1889. }
  1890. generate( /*builder, output*/ ) {
  1891. console.warn( 'Abstract function.' );
  1892. }
  1893. }
  1894. const _regNum = /float|u?int/;
  1895. /**
  1896. * Class for representing a constant value in the shader.
  1897. *
  1898. * @augments InputNode
  1899. */
  1900. class ConstNode extends InputNode {
  1901. static get type() {
  1902. return 'ConstNode';
  1903. }
  1904. /**
  1905. * Constructs a new input node.
  1906. *
  1907. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1908. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1909. */
  1910. constructor( value, nodeType = null ) {
  1911. super( value, nodeType );
  1912. /**
  1913. * This flag can be used for type testing.
  1914. *
  1915. * @type {Boolean}
  1916. * @readonly
  1917. * @default true
  1918. */
  1919. this.isConstNode = true;
  1920. }
  1921. /**
  1922. * Generates the shader string of the value with the current node builder.
  1923. *
  1924. * @param {NodeBuilder} builder - The current node builder.
  1925. * @return {String} The generated value as a shader string.
  1926. */
  1927. generateConst( builder ) {
  1928. return builder.generateConst( this.getNodeType( builder ), this.value );
  1929. }
  1930. generate( builder, output ) {
  1931. const type = this.getNodeType( builder );
  1932. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  1933. return builder.generateConst( output, this.value );
  1934. }
  1935. return builder.format( this.generateConst( builder ), type, output );
  1936. }
  1937. }
  1938. /**
  1939. * Base class for representing member access on an object-like
  1940. * node data structures.
  1941. *
  1942. * @augments Node
  1943. */
  1944. class MemberNode extends Node {
  1945. static get type() {
  1946. return 'MemberNode';
  1947. }
  1948. /**
  1949. * Constructs an array element node.
  1950. *
  1951. * @param {Node} node - The array-like node.
  1952. * @param {String} property - The property name.
  1953. */
  1954. constructor( node, property ) {
  1955. super();
  1956. /**
  1957. * The array-like node.
  1958. *
  1959. * @type {Node}
  1960. */
  1961. this.node = node;
  1962. /**
  1963. * The property name.
  1964. *
  1965. * @type {Node}
  1966. */
  1967. this.property = property;
  1968. /**
  1969. * This flag can be used for type testing.
  1970. *
  1971. * @type {Boolean}
  1972. * @readonly
  1973. * @default true
  1974. */
  1975. this.isMemberNode = true;
  1976. }
  1977. getNodeType( builder ) {
  1978. return this.node.getMemberType( builder, this.property );
  1979. }
  1980. generate( builder ) {
  1981. const propertyName = this.node.build( builder );
  1982. return propertyName + '.' + this.property;
  1983. }
  1984. }
  1985. /** @module TSLCore **/
  1986. let currentStack = null;
  1987. const NodeElements = new Map();
  1988. function addMethodChaining( name, nodeElement ) {
  1989. if ( NodeElements.has( name ) ) {
  1990. console.warn( `Redefinition of method chaining ${ name }` );
  1991. return;
  1992. }
  1993. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1994. NodeElements.set( name, nodeElement );
  1995. }
  1996. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1997. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1998. const shaderNodeHandler = {
  1999. setup( NodeClosure, params ) {
  2000. const inputs = params.shift();
  2001. return NodeClosure( nodeObjects( inputs ), ...params );
  2002. },
  2003. get( node, prop, nodeObj ) {
  2004. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2005. if ( node.isStackNode !== true && prop === 'assign' ) {
  2006. return ( ...params ) => {
  2007. currentStack.assign( nodeObj, ...params );
  2008. return nodeObj;
  2009. };
  2010. } else if ( NodeElements.has( prop ) ) {
  2011. const nodeElement = NodeElements.get( prop );
  2012. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2013. } else if ( prop === 'self' ) {
  2014. return node;
  2015. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2016. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2017. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2018. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2019. // accessing properties ( swizzle )
  2020. prop = parseSwizzle( prop );
  2021. return nodeObject( new SplitNode( nodeObj, prop ) );
  2022. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2023. // set properties ( swizzle ) and sort to xyzw sequence
  2024. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2025. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  2026. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2027. // set properties ( swizzle ) and sort to xyzw sequence
  2028. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2029. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2030. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2031. // accessing property
  2032. if ( prop === 'width' ) prop = 'x';
  2033. else if ( prop === 'height' ) prop = 'y';
  2034. else if ( prop === 'depth' ) prop = 'z';
  2035. return nodeObject( new SplitNode( node, prop ) );
  2036. } else if ( /^\d+$/.test( prop ) === true ) {
  2037. // accessing array
  2038. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2039. } else if ( /^get$/.test( prop ) === true ) {
  2040. // accessing properties
  2041. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2042. }
  2043. }
  2044. return Reflect.get( node, prop, nodeObj );
  2045. },
  2046. set( node, prop, value, nodeObj ) {
  2047. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2048. // setting properties
  2049. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2050. nodeObj[ prop ].assign( value );
  2051. return true;
  2052. }
  2053. }
  2054. return Reflect.set( node, prop, value, nodeObj );
  2055. }
  2056. };
  2057. const nodeObjectsCacheMap = new WeakMap();
  2058. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2059. const ShaderNodeObject = function ( obj, altType = null ) {
  2060. const type = getValueType( obj );
  2061. if ( type === 'node' ) {
  2062. let nodeObject = nodeObjectsCacheMap.get( obj );
  2063. if ( nodeObject === undefined ) {
  2064. nodeObject = new Proxy( obj, shaderNodeHandler );
  2065. nodeObjectsCacheMap.set( obj, nodeObject );
  2066. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2067. }
  2068. return nodeObject;
  2069. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2070. return nodeObject( getConstNode( obj, altType ) );
  2071. } else if ( type === 'shader' ) {
  2072. return Fn( obj );
  2073. }
  2074. return obj;
  2075. };
  2076. const ShaderNodeObjects = function ( objects, altType = null ) {
  2077. for ( const name in objects ) {
  2078. objects[ name ] = nodeObject( objects[ name ], altType );
  2079. }
  2080. return objects;
  2081. };
  2082. const ShaderNodeArray = function ( array, altType = null ) {
  2083. const len = array.length;
  2084. for ( let i = 0; i < len; i ++ ) {
  2085. array[ i ] = nodeObject( array[ i ], altType );
  2086. }
  2087. return array;
  2088. };
  2089. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2090. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2091. if ( scope === null ) {
  2092. return ( ...params ) => {
  2093. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2094. };
  2095. } else if ( factor !== null ) {
  2096. factor = nodeObject( factor );
  2097. return ( ...params ) => {
  2098. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2099. };
  2100. } else {
  2101. return ( ...params ) => {
  2102. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2103. };
  2104. }
  2105. };
  2106. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2107. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2108. };
  2109. class ShaderCallNodeInternal extends Node {
  2110. constructor( shaderNode, inputNodes ) {
  2111. super();
  2112. this.shaderNode = shaderNode;
  2113. this.inputNodes = inputNodes;
  2114. }
  2115. getNodeType( builder ) {
  2116. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2117. }
  2118. getMemberType( builder, name ) {
  2119. return this.getOutputNode( builder ).getMemberType( builder, name );
  2120. }
  2121. call( builder ) {
  2122. const { shaderNode, inputNodes } = this;
  2123. const properties = builder.getNodeProperties( shaderNode );
  2124. if ( properties.onceOutput ) return properties.onceOutput;
  2125. //
  2126. let result = null;
  2127. if ( shaderNode.layout ) {
  2128. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2129. if ( functionNodesCacheMap === undefined ) {
  2130. functionNodesCacheMap = new WeakMap();
  2131. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2132. }
  2133. let functionNode = functionNodesCacheMap.get( shaderNode );
  2134. if ( functionNode === undefined ) {
  2135. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2136. functionNodesCacheMap.set( shaderNode, functionNode );
  2137. }
  2138. if ( builder.currentFunctionNode !== null ) {
  2139. builder.currentFunctionNode.includes.push( functionNode );
  2140. }
  2141. result = nodeObject( functionNode.call( inputNodes ) );
  2142. } else {
  2143. const jsFunc = shaderNode.jsFunc;
  2144. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2145. result = nodeObject( outputNode );
  2146. }
  2147. if ( shaderNode.once ) {
  2148. properties.onceOutput = result;
  2149. }
  2150. return result;
  2151. }
  2152. getOutputNode( builder ) {
  2153. const properties = builder.getNodeProperties( this );
  2154. if ( properties.outputNode === null ) {
  2155. properties.outputNode = this.setupOutput( builder );
  2156. }
  2157. return properties.outputNode;
  2158. }
  2159. setup( builder ) {
  2160. return this.getOutputNode( builder );
  2161. }
  2162. setupOutput( builder ) {
  2163. builder.addStack();
  2164. builder.stack.outputNode = this.call( builder );
  2165. return builder.removeStack();
  2166. }
  2167. generate( builder, output ) {
  2168. const outputNode = this.getOutputNode( builder );
  2169. return outputNode.build( builder, output );
  2170. }
  2171. }
  2172. class ShaderNodeInternal extends Node {
  2173. constructor( jsFunc, nodeType ) {
  2174. super( nodeType );
  2175. this.jsFunc = jsFunc;
  2176. this.layout = null;
  2177. this.global = true;
  2178. this.once = false;
  2179. }
  2180. setLayout( layout ) {
  2181. this.layout = layout;
  2182. return this;
  2183. }
  2184. call( inputs = null ) {
  2185. nodeObjects( inputs );
  2186. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2187. }
  2188. setup() {
  2189. return this.call();
  2190. }
  2191. }
  2192. const bools = [ false, true ];
  2193. const uints = [ 0, 1, 2, 3 ];
  2194. const ints = [ - 1, - 2 ];
  2195. 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 ];
  2196. const boolsCacheMap = new Map();
  2197. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2198. const uintsCacheMap = new Map();
  2199. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2200. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2201. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2202. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2203. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2204. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2205. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2206. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2207. const getConstNode = ( value, type ) => {
  2208. if ( constNodesCacheMap.has( value ) ) {
  2209. return constNodesCacheMap.get( value );
  2210. } else if ( value.isNode === true ) {
  2211. return value;
  2212. } else {
  2213. return new ConstNode( value, type );
  2214. }
  2215. };
  2216. const safeGetNodeType = ( node ) => {
  2217. try {
  2218. return node.getNodeType();
  2219. } catch ( _ ) {
  2220. return undefined;
  2221. }
  2222. };
  2223. const ConvertType = function ( type, cacheMap = null ) {
  2224. return ( ...params ) => {
  2225. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2226. params = [ getValueFromType( type, ...params ) ];
  2227. }
  2228. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2229. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2230. }
  2231. if ( params.length === 1 ) {
  2232. const node = getConstNode( params[ 0 ], type );
  2233. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2234. return nodeObject( new ConvertNode( node, type ) );
  2235. }
  2236. const nodes = params.map( param => getConstNode( param ) );
  2237. return nodeObject( new JoinNode( nodes, type ) );
  2238. };
  2239. };
  2240. // exports
  2241. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2242. // utils
  2243. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2244. // shader node base
  2245. function ShaderNode( jsFunc, nodeType ) {
  2246. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2247. }
  2248. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2249. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2250. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2251. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2252. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2253. const Fn = ( jsFunc, nodeType ) => {
  2254. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2255. const fn = ( ...params ) => {
  2256. let inputs;
  2257. nodeObjects( params );
  2258. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2259. inputs = [ ...params ];
  2260. } else {
  2261. inputs = params[ 0 ];
  2262. }
  2263. return shaderNode.call( inputs );
  2264. };
  2265. fn.shaderNode = shaderNode;
  2266. fn.setLayout = ( layout ) => {
  2267. shaderNode.setLayout( layout );
  2268. return fn;
  2269. };
  2270. fn.once = () => {
  2271. shaderNode.once = true;
  2272. return fn;
  2273. };
  2274. return fn;
  2275. };
  2276. /**
  2277. * @function
  2278. * @deprecated since r168. Use {@link Fn} instead.
  2279. *
  2280. * @param {...any} params
  2281. * @returns {Function}
  2282. */
  2283. const tslFn = ( ...params ) => { // @deprecated, r168
  2284. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2285. return Fn( ...params );
  2286. };
  2287. //
  2288. addMethodChaining( 'toGlobal', ( node ) => {
  2289. node.global = true;
  2290. return node;
  2291. } );
  2292. //
  2293. const setCurrentStack = ( stack ) => {
  2294. currentStack = stack;
  2295. };
  2296. const getCurrentStack = () => currentStack;
  2297. const If = ( ...params ) => currentStack.If( ...params );
  2298. function append( node ) {
  2299. if ( currentStack ) currentStack.add( node );
  2300. return node;
  2301. }
  2302. addMethodChaining( 'append', append );
  2303. // types
  2304. const color = new ConvertType( 'color' );
  2305. const float = new ConvertType( 'float', cacheMaps.float );
  2306. const int = new ConvertType( 'int', cacheMaps.ints );
  2307. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2308. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2309. const vec2 = new ConvertType( 'vec2' );
  2310. const ivec2 = new ConvertType( 'ivec2' );
  2311. const uvec2 = new ConvertType( 'uvec2' );
  2312. const bvec2 = new ConvertType( 'bvec2' );
  2313. const vec3 = new ConvertType( 'vec3' );
  2314. const ivec3 = new ConvertType( 'ivec3' );
  2315. const uvec3 = new ConvertType( 'uvec3' );
  2316. const bvec3 = new ConvertType( 'bvec3' );
  2317. const vec4 = new ConvertType( 'vec4' );
  2318. const ivec4 = new ConvertType( 'ivec4' );
  2319. const uvec4 = new ConvertType( 'uvec4' );
  2320. const bvec4 = new ConvertType( 'bvec4' );
  2321. const mat2 = new ConvertType( 'mat2' );
  2322. const mat3 = new ConvertType( 'mat3' );
  2323. const mat4 = new ConvertType( 'mat4' );
  2324. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2325. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2326. addMethodChaining( 'toColor', color );
  2327. addMethodChaining( 'toFloat', float );
  2328. addMethodChaining( 'toInt', int );
  2329. addMethodChaining( 'toUint', uint );
  2330. addMethodChaining( 'toBool', bool );
  2331. addMethodChaining( 'toVec2', vec2 );
  2332. addMethodChaining( 'toIVec2', ivec2 );
  2333. addMethodChaining( 'toUVec2', uvec2 );
  2334. addMethodChaining( 'toBVec2', bvec2 );
  2335. addMethodChaining( 'toVec3', vec3 );
  2336. addMethodChaining( 'toIVec3', ivec3 );
  2337. addMethodChaining( 'toUVec3', uvec3 );
  2338. addMethodChaining( 'toBVec3', bvec3 );
  2339. addMethodChaining( 'toVec4', vec4 );
  2340. addMethodChaining( 'toIVec4', ivec4 );
  2341. addMethodChaining( 'toUVec4', uvec4 );
  2342. addMethodChaining( 'toBVec4', bvec4 );
  2343. addMethodChaining( 'toMat2', mat2 );
  2344. addMethodChaining( 'toMat3', mat3 );
  2345. addMethodChaining( 'toMat4', mat4 );
  2346. // basic nodes
  2347. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2348. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2349. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2350. addMethodChaining( 'element', element );
  2351. addMethodChaining( 'convert', convert );
  2352. /** @module ArrayNode **/
  2353. /**
  2354. * ArrayNode represents a collection of nodes, typically created using the {@link module:TSL~array} function.
  2355. * ```js
  2356. * const colors = array( [
  2357. * vec3( 1, 0, 0 ),
  2358. * vec3( 0, 1, 0 ),
  2359. * vec3( 0, 0, 1 )
  2360. * ] );
  2361. *
  2362. * const redColor = tintColors.element( 0 );
  2363. *
  2364. * @augments Node
  2365. */
  2366. class ArrayNode extends TempNode {
  2367. static get type() {
  2368. return 'ArrayNode';
  2369. }
  2370. /**
  2371. * Constructs a new array node.
  2372. *
  2373. * @param {String} [nodeType] - The data type of the elements.
  2374. * @param {Number} [count] - Size of the array.
  2375. * @param {Array<Node>?} [values=null] - Array default values.
  2376. */
  2377. constructor( nodeType, count, values = null ) {
  2378. super( nodeType );
  2379. /**
  2380. * Array size.
  2381. *
  2382. * @type {Array<Node>}
  2383. */
  2384. this.count = count;
  2385. /**
  2386. * Array default values.
  2387. *
  2388. * @type {Array<Node>}
  2389. */
  2390. this.values = values;
  2391. /**
  2392. * This flag can be used for type testing.
  2393. *
  2394. * @type {Boolean}
  2395. * @readonly
  2396. * @default true
  2397. */
  2398. this.isArrayNode = true;
  2399. }
  2400. getNodeType( builder ) {
  2401. if ( this.nodeType === null ) {
  2402. this.nodeType = this.values[ 0 ].getNodeType( builder );
  2403. }
  2404. return this.nodeType;
  2405. }
  2406. getElementType( builder ) {
  2407. return this.getNodeType( builder );
  2408. }
  2409. generate( builder ) {
  2410. const type = this.getNodeType( builder );
  2411. return builder.generateArray( type, this.count, this.values );
  2412. }
  2413. }
  2414. /**
  2415. * TSL function for creating an array node.
  2416. *
  2417. * @function
  2418. * @param {String|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  2419. * or an array containing the default values (e.g., [ vec3() ]).
  2420. * @param {Number?} [count] - Size of the array.
  2421. * @returns {ArrayNode}
  2422. */
  2423. const array = ( ...params ) => {
  2424. let node;
  2425. if ( params.length === 1 ) {
  2426. const values = params[ 0 ];
  2427. node = new ArrayNode( null, values.length, values );
  2428. } else {
  2429. const nodeType = params[ 0 ];
  2430. const count = params[ 1 ];
  2431. node = new ArrayNode( nodeType, count );
  2432. }
  2433. return nodeObject( node );
  2434. };
  2435. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  2436. /** @module UniformGroupNode **/
  2437. /**
  2438. * This node can be used to group single instances of {@link UniformNode}
  2439. * and manage them as a uniform buffer.
  2440. *
  2441. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2442. * will be used when defining the {@link UniformNode#groupNode} property.
  2443. *
  2444. * - `objectGroup`: Uniform buffer per object.
  2445. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2446. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2447. *
  2448. * @augments Node
  2449. */
  2450. class UniformGroupNode extends Node {
  2451. static get type() {
  2452. return 'UniformGroupNode';
  2453. }
  2454. /**
  2455. * Constructs a new uniform group node.
  2456. *
  2457. * @param {String} name - The name of the uniform group node.
  2458. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2459. * @param {Number} [order=1] - Influences the internal sorting.
  2460. */
  2461. constructor( name, shared = false, order = 1 ) {
  2462. super( 'string' );
  2463. /**
  2464. * The name of the uniform group node.
  2465. *
  2466. * @type {String}
  2467. */
  2468. this.name = name;
  2469. /**
  2470. * Whether this uniform group node is shared or not.
  2471. *
  2472. * @type {Boolean}
  2473. * @default false
  2474. */
  2475. this.shared = shared;
  2476. /**
  2477. * Influences the internal sorting.
  2478. * TODO: Add details when this property should be changed.
  2479. *
  2480. * @type {Number}
  2481. * @default 1
  2482. */
  2483. this.order = order;
  2484. /**
  2485. * This flag can be used for type testing.
  2486. *
  2487. * @type {Boolean}
  2488. * @readonly
  2489. * @default true
  2490. */
  2491. this.isUniformGroup = true;
  2492. }
  2493. serialize( data ) {
  2494. super.serialize( data );
  2495. data.name = this.name;
  2496. data.version = this.version;
  2497. data.shared = this.shared;
  2498. }
  2499. deserialize( data ) {
  2500. super.deserialize( data );
  2501. this.name = data.name;
  2502. this.version = data.version;
  2503. this.shared = data.shared;
  2504. }
  2505. }
  2506. /**
  2507. * TSL function for creating a uniform group node with the given name.
  2508. *
  2509. * @function
  2510. * @param {String} name - The name of the uniform group node.
  2511. * @returns {UniformGroupNode}
  2512. */
  2513. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2514. /**
  2515. * TSL function for creating a shared uniform group node with the given name and order.
  2516. *
  2517. * @function
  2518. * @param {String} name - The name of the uniform group node.
  2519. * @param {Number} [order=0] - Influences the internal sorting.
  2520. * @returns {UniformGroupNode}
  2521. */
  2522. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2523. /**
  2524. * TSL object that represents a shared uniform group node which is updated once per frame.
  2525. *
  2526. * @type {UniformGroupNode}
  2527. */
  2528. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2529. /**
  2530. * TSL object that represents a shared uniform group node which is updated once per render.
  2531. *
  2532. * @type {UniformGroupNode}
  2533. */
  2534. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2535. /**
  2536. * TSL object that represents a uniform group node which is updated once per object.
  2537. *
  2538. * @type {UniformGroupNode}
  2539. */
  2540. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2541. /** @module UniformNode **/
  2542. /**
  2543. * Class for representing a uniform.
  2544. *
  2545. * @augments InputNode
  2546. */
  2547. class UniformNode extends InputNode {
  2548. static get type() {
  2549. return 'UniformNode';
  2550. }
  2551. /**
  2552. * Constructs a new uniform node.
  2553. *
  2554. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2555. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2556. */
  2557. constructor( value, nodeType = null ) {
  2558. super( value, nodeType );
  2559. /**
  2560. * This flag can be used for type testing.
  2561. *
  2562. * @type {Boolean}
  2563. * @readonly
  2564. * @default true
  2565. */
  2566. this.isUniformNode = true;
  2567. /**
  2568. * The name or label of the uniform.
  2569. *
  2570. * @type {String}
  2571. * @default ''
  2572. */
  2573. this.name = '';
  2574. /**
  2575. * The uniform group of this uniform. By default, uniforms are
  2576. * managed per object but they might belong to a shared group
  2577. * which is updated per frame or render call.
  2578. *
  2579. * @type {UniformGroupNode}
  2580. */
  2581. this.groupNode = objectGroup;
  2582. }
  2583. /**
  2584. * Sets the {@link UniformNode#name} property.
  2585. *
  2586. * @param {String} name - The name of the uniform.
  2587. * @return {UniformNode} A reference to this node.
  2588. */
  2589. label( name ) {
  2590. this.name = name;
  2591. return this;
  2592. }
  2593. /**
  2594. * Sets the {@link UniformNode#groupNode} property.
  2595. *
  2596. * @param {UniformGroupNode} group - The uniform group.
  2597. * @return {UniformNode} A reference to this node.
  2598. */
  2599. setGroup( group ) {
  2600. this.groupNode = group;
  2601. return this;
  2602. }
  2603. /**
  2604. * Returns the {@link UniformNode#groupNode}.
  2605. *
  2606. * @return {UniformGroupNode} The uniform group.
  2607. */
  2608. getGroup() {
  2609. return this.groupNode;
  2610. }
  2611. /**
  2612. * By default, this method returns the result of {@link Node#getHash} but derived
  2613. * classes might overwrite this method with a different implementation.
  2614. *
  2615. * @param {NodeBuilder} builder - The current node builder.
  2616. * @return {String} The uniform hash.
  2617. */
  2618. getUniformHash( builder ) {
  2619. return this.getHash( builder );
  2620. }
  2621. onUpdate( callback, updateType ) {
  2622. const self = this.getSelf();
  2623. callback = callback.bind( self );
  2624. return super.onUpdate( ( frame ) => {
  2625. const value = callback( frame, self );
  2626. if ( value !== undefined ) {
  2627. this.value = value;
  2628. }
  2629. }, updateType );
  2630. }
  2631. generate( builder, output ) {
  2632. const type = this.getNodeType( builder );
  2633. const hash = this.getUniformHash( builder );
  2634. let sharedNode = builder.getNodeFromHash( hash );
  2635. if ( sharedNode === undefined ) {
  2636. builder.setHashNode( this, hash );
  2637. sharedNode = this;
  2638. }
  2639. const sharedNodeType = sharedNode.getInputType( builder );
  2640. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2641. const propertyName = builder.getPropertyName( nodeUniform );
  2642. if ( builder.context.label !== undefined ) delete builder.context.label;
  2643. return builder.format( propertyName, type, output );
  2644. }
  2645. }
  2646. /**
  2647. * TSL function for creating a uniform node.
  2648. *
  2649. * @function
  2650. * @param {Any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2651. * @param {String?} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2652. * @returns {UniformNode}
  2653. */
  2654. const uniform = ( arg1, arg2 ) => {
  2655. const nodeType = getConstNodeType( arg2 || arg1 );
  2656. // @TODO: get ConstNode from .traverse() in the future
  2657. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2658. return nodeObject( new UniformNode( value, nodeType ) );
  2659. };
  2660. /** @module PropertyNode **/
  2661. /**
  2662. * This class represents a shader property. It can be used
  2663. * to explicitly define a property and assign a value to it.
  2664. *
  2665. * ```js
  2666. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2667. *```
  2668. * `PropertyNode` is used by the engine to predefined common material properties
  2669. * for TSL code.
  2670. *
  2671. * @augments Node
  2672. */
  2673. class PropertyNode extends Node {
  2674. static get type() {
  2675. return 'PropertyNode';
  2676. }
  2677. /**
  2678. * Constructs a new property node.
  2679. *
  2680. * @param {String} nodeType - The type of the node.
  2681. * @param {String?} [name=null] - The name of the property in the shader.
  2682. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2683. */
  2684. constructor( nodeType, name = null, varying = false ) {
  2685. super( nodeType );
  2686. /**
  2687. * The name of the property in the shader. If no name is defined,
  2688. * the node system auto-generates one.
  2689. *
  2690. * @type {String?}
  2691. * @default null
  2692. */
  2693. this.name = name;
  2694. /**
  2695. * Whether this property is a varying or not.
  2696. *
  2697. * @type {Boolean}
  2698. * @default false
  2699. */
  2700. this.varying = varying;
  2701. /**
  2702. * This flag can be used for type testing.
  2703. *
  2704. * @type {Boolean}
  2705. * @readonly
  2706. * @default true
  2707. */
  2708. this.isPropertyNode = true;
  2709. }
  2710. getHash( builder ) {
  2711. return this.name || super.getHash( builder );
  2712. }
  2713. /**
  2714. * The method is overwritten so it always returns `true`.
  2715. *
  2716. * @param {NodeBuilder} builder - The current node builder.
  2717. * @return {Boolean} Whether this node is global or not.
  2718. */
  2719. isGlobal( /*builder*/ ) {
  2720. return true;
  2721. }
  2722. generate( builder ) {
  2723. let nodeVar;
  2724. if ( this.varying === true ) {
  2725. nodeVar = builder.getVaryingFromNode( this, this.name );
  2726. nodeVar.needsInterpolation = true;
  2727. } else {
  2728. nodeVar = builder.getVarFromNode( this, this.name );
  2729. }
  2730. return builder.getPropertyName( nodeVar );
  2731. }
  2732. }
  2733. /**
  2734. * TSL function for creating a property node.
  2735. *
  2736. * @function
  2737. * @param {String} type - The type of the node.
  2738. * @param {String?} [name=null] - The name of the property in the shader.
  2739. * @returns {PropertyNode}
  2740. */
  2741. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2742. /**
  2743. * TSL function for creating a varying property node.
  2744. *
  2745. * @function
  2746. * @param {String} type - The type of the node.
  2747. * @param {String?} [name=null] - The name of the varying in the shader.
  2748. * @returns {PropertyNode}
  2749. */
  2750. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2751. /**
  2752. * TSL object that represents the shader variable `DiffuseColor`.
  2753. *
  2754. * @type {PropertyNode<vec4>}
  2755. */
  2756. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2757. /**
  2758. * TSL object that represents the shader variable `EmissiveColor`.
  2759. *
  2760. * @type {PropertyNode<vec3>}
  2761. */
  2762. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2763. /**
  2764. * TSL object that represents the shader variable `Roughness`.
  2765. *
  2766. * @type {PropertyNode<float>}
  2767. */
  2768. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2769. /**
  2770. * TSL object that represents the shader variable `Metalness`.
  2771. *
  2772. * @type {PropertyNode<float>}
  2773. */
  2774. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2775. /**
  2776. * TSL object that represents the shader variable `Clearcoat`.
  2777. *
  2778. * @type {PropertyNode<float>}
  2779. */
  2780. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2781. /**
  2782. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2783. *
  2784. * @type {PropertyNode<float>}
  2785. */
  2786. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2787. /**
  2788. * TSL object that represents the shader variable `Sheen`.
  2789. *
  2790. * @type {PropertyNode<vec3>}
  2791. */
  2792. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2793. /**
  2794. * TSL object that represents the shader variable `SheenRoughness`.
  2795. *
  2796. * @type {PropertyNode<float>}
  2797. */
  2798. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2799. /**
  2800. * TSL object that represents the shader variable `Iridescence`.
  2801. *
  2802. * @type {PropertyNode<float>}
  2803. */
  2804. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2805. /**
  2806. * TSL object that represents the shader variable `IridescenceIOR`.
  2807. *
  2808. * @type {PropertyNode<float>}
  2809. */
  2810. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2811. /**
  2812. * TSL object that represents the shader variable `IridescenceThickness`.
  2813. *
  2814. * @type {PropertyNode<float>}
  2815. */
  2816. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2817. /**
  2818. * TSL object that represents the shader variable `AlphaT`.
  2819. *
  2820. * @type {PropertyNode<float>}
  2821. */
  2822. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2823. /**
  2824. * TSL object that represents the shader variable `Anisotropy`.
  2825. *
  2826. * @type {PropertyNode<float>}
  2827. */
  2828. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2829. /**
  2830. * TSL object that represents the shader variable `AnisotropyT`.
  2831. *
  2832. * @type {PropertyNode<vec3>}
  2833. */
  2834. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2835. /**
  2836. * TSL object that represents the shader variable `AnisotropyB`.
  2837. *
  2838. * @type {PropertyNode<vec3>}
  2839. */
  2840. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2841. /**
  2842. * TSL object that represents the shader variable `SpecularColor`.
  2843. *
  2844. * @type {PropertyNode<color>}
  2845. */
  2846. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2847. /**
  2848. * TSL object that represents the shader variable `SpecularF90`.
  2849. *
  2850. * @type {PropertyNode<float>}
  2851. */
  2852. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2853. /**
  2854. * TSL object that represents the shader variable `Shininess`.
  2855. *
  2856. * @type {PropertyNode<float>}
  2857. */
  2858. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2859. /**
  2860. * TSL object that represents the shader variable `Output`.
  2861. *
  2862. * @type {PropertyNode<vec4>}
  2863. */
  2864. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2865. /**
  2866. * TSL object that represents the shader variable `dashSize`.
  2867. *
  2868. * @type {PropertyNode<float>}
  2869. */
  2870. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2871. /**
  2872. * TSL object that represents the shader variable `gapSize`.
  2873. *
  2874. * @type {PropertyNode<float>}
  2875. */
  2876. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2877. /**
  2878. * TSL object that represents the shader variable `pointWidth`.
  2879. *
  2880. * @type {PropertyNode<float>}
  2881. */
  2882. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2883. /**
  2884. * TSL object that represents the shader variable `IOR`.
  2885. *
  2886. * @type {PropertyNode<float>}
  2887. */
  2888. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2889. /**
  2890. * TSL object that represents the shader variable `Transmission`.
  2891. *
  2892. * @type {PropertyNode<float>}
  2893. */
  2894. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2895. /**
  2896. * TSL object that represents the shader variable `Thickness`.
  2897. *
  2898. * @type {PropertyNode<float>}
  2899. */
  2900. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2901. /**
  2902. * TSL object that represents the shader variable `AttenuationDistance`.
  2903. *
  2904. * @type {PropertyNode<float>}
  2905. */
  2906. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2907. /**
  2908. * TSL object that represents the shader variable `AttenuationColor`.
  2909. *
  2910. * @type {PropertyNode<color>}
  2911. */
  2912. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2913. /**
  2914. * TSL object that represents the shader variable `Dispersion`.
  2915. *
  2916. * @type {PropertyNode<float>}
  2917. */
  2918. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2919. /** @module AssignNode **/
  2920. /**
  2921. * These node represents an assign operation. Meaning a node is assigned
  2922. * to another node.
  2923. *
  2924. * @augments TempNode
  2925. */
  2926. class AssignNode extends TempNode {
  2927. static get type() {
  2928. return 'AssignNode';
  2929. }
  2930. /**
  2931. * Constructs a new assign node.
  2932. *
  2933. * @param {Node} targetNode - The target node.
  2934. * @param {Node} sourceNode - The source type.
  2935. */
  2936. constructor( targetNode, sourceNode ) {
  2937. super();
  2938. /**
  2939. * The target node.
  2940. *
  2941. * @type {Node}
  2942. */
  2943. this.targetNode = targetNode;
  2944. /**
  2945. * The source node.
  2946. *
  2947. * @type {Node}
  2948. */
  2949. this.sourceNode = sourceNode;
  2950. }
  2951. /**
  2952. * Whether this node is used more than once in context of other nodes. This method
  2953. * is overwritten since it always returns `false` (assigns are unique).
  2954. *
  2955. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2956. */
  2957. hasDependencies() {
  2958. return false;
  2959. }
  2960. getNodeType( builder, output ) {
  2961. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2962. }
  2963. /**
  2964. * Whether a split is required when assigning source to target. This can happen when the component length of
  2965. * target and source data type does not match.
  2966. *
  2967. * @param {NodeBuilder} builder - The current node builder.
  2968. * @return {Boolean} Whether a split is required when assigning source to target.
  2969. */
  2970. needsSplitAssign( builder ) {
  2971. const { targetNode } = this;
  2972. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2973. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2974. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2975. return assignDifferentVector;
  2976. }
  2977. return false;
  2978. }
  2979. generate( builder, output ) {
  2980. const { targetNode, sourceNode } = this;
  2981. const needsSplitAssign = this.needsSplitAssign( builder );
  2982. const targetType = targetNode.getNodeType( builder );
  2983. const target = targetNode.context( { assign: true } ).build( builder );
  2984. const source = sourceNode.build( builder, targetType );
  2985. const sourceType = sourceNode.getNodeType( builder );
  2986. const nodeData = builder.getDataFromNode( this );
  2987. //
  2988. let snippet;
  2989. if ( nodeData.initialized === true ) {
  2990. if ( output !== 'void' ) {
  2991. snippet = target;
  2992. }
  2993. } else if ( needsSplitAssign ) {
  2994. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2995. const sourceProperty = builder.getPropertyName( sourceVar );
  2996. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2997. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2998. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2999. const component = targetNode.components[ i ];
  3000. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3001. }
  3002. if ( output !== 'void' ) {
  3003. snippet = target;
  3004. }
  3005. } else {
  3006. snippet = `${ target } = ${ source }`;
  3007. if ( output === 'void' || sourceType === 'void' ) {
  3008. builder.addLineFlowCode( snippet, this );
  3009. if ( output !== 'void' ) {
  3010. snippet = target;
  3011. }
  3012. }
  3013. }
  3014. nodeData.initialized = true;
  3015. return builder.format( snippet, targetType, output );
  3016. }
  3017. }
  3018. /**
  3019. * TSL function for creating an assign node.
  3020. *
  3021. * @function
  3022. * @param {Node} targetNode - The target node.
  3023. * @param {Node} sourceNode - The source type.
  3024. * @returns {AssignNode}
  3025. */
  3026. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  3027. addMethodChaining( 'assign', assign );
  3028. /**
  3029. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3030. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3031. * this logic.
  3032. *
  3033. * @augments TempNode
  3034. */
  3035. class FunctionCallNode extends TempNode {
  3036. static get type() {
  3037. return 'FunctionCallNode';
  3038. }
  3039. /**
  3040. * Constructs a new function call node.
  3041. *
  3042. * @param {FunctionNode?} functionNode - The function node.
  3043. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  3044. */
  3045. constructor( functionNode = null, parameters = {} ) {
  3046. super();
  3047. /**
  3048. * The function node.
  3049. *
  3050. * @type {FunctionNode}
  3051. * @default null
  3052. */
  3053. this.functionNode = functionNode;
  3054. /**
  3055. * The parameters of the function call.
  3056. *
  3057. * @type {Object<String, Node>}
  3058. * @default {}
  3059. */
  3060. this.parameters = parameters;
  3061. }
  3062. /**
  3063. * Sets the parameters of the function call node.
  3064. *
  3065. * @param {Object<String, Node>} parameters - The parameters to set.
  3066. * @return {FunctionCallNode} A reference to this node.
  3067. */
  3068. setParameters( parameters ) {
  3069. this.parameters = parameters;
  3070. return this;
  3071. }
  3072. /**
  3073. * Returns the parameters of the function call node.
  3074. *
  3075. * @return {Object<String, Node>} The parameters of this node.
  3076. */
  3077. getParameters() {
  3078. return this.parameters;
  3079. }
  3080. getNodeType( builder ) {
  3081. return this.functionNode.getNodeType( builder );
  3082. }
  3083. generate( builder ) {
  3084. const params = [];
  3085. const functionNode = this.functionNode;
  3086. const inputs = functionNode.getInputs( builder );
  3087. const parameters = this.parameters;
  3088. const generateInput = ( node, inputNode ) => {
  3089. const type = inputNode.type;
  3090. const pointer = type === 'pointer';
  3091. let output;
  3092. if ( pointer ) output = '&' + node.build( builder );
  3093. else output = node.build( builder, type );
  3094. return output;
  3095. };
  3096. if ( Array.isArray( parameters ) ) {
  3097. for ( let i = 0; i < parameters.length; i ++ ) {
  3098. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3099. }
  3100. } else {
  3101. for ( const inputNode of inputs ) {
  3102. const node = parameters[ inputNode.name ];
  3103. if ( node !== undefined ) {
  3104. params.push( generateInput( node, inputNode ) );
  3105. } else {
  3106. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  3107. }
  3108. }
  3109. }
  3110. const functionName = functionNode.build( builder, 'property' );
  3111. return `${functionName}( ${params.join( ', ' )} )`;
  3112. }
  3113. }
  3114. const call = ( func, ...params ) => {
  3115. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3116. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3117. };
  3118. addMethodChaining( 'call', call );
  3119. /** @module OperatorNode **/
  3120. /**
  3121. * This node represents basic mathematical and logical operations like addition,
  3122. * subtraction or comparisons (e.g. `equal()`).
  3123. *
  3124. * @augments TempNode
  3125. */
  3126. class OperatorNode extends TempNode {
  3127. static get type() {
  3128. return 'OperatorNode';
  3129. }
  3130. /**
  3131. * Constructs a new operator node.
  3132. *
  3133. * @param {String} op - The operator.
  3134. * @param {Node} aNode - The first input.
  3135. * @param {Node} bNode - The second input.
  3136. * @param {...Node} params - Additional input parameters.
  3137. */
  3138. constructor( op, aNode, bNode, ...params ) {
  3139. super();
  3140. if ( params.length > 0 ) {
  3141. let finalOp = new OperatorNode( op, aNode, bNode );
  3142. for ( let i = 0; i < params.length - 1; i ++ ) {
  3143. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3144. }
  3145. aNode = finalOp;
  3146. bNode = params[ params.length - 1 ];
  3147. }
  3148. /**
  3149. * The operator.
  3150. *
  3151. * @type {String}
  3152. */
  3153. this.op = op;
  3154. /**
  3155. * The first input.
  3156. *
  3157. * @type {Node}
  3158. */
  3159. this.aNode = aNode;
  3160. /**
  3161. * The second input.
  3162. *
  3163. * @type {Node}
  3164. */
  3165. this.bNode = bNode;
  3166. /**
  3167. * This flag can be used for type testing.
  3168. *
  3169. * @type {Boolean}
  3170. * @readonly
  3171. * @default true
  3172. */
  3173. this.isOperatorNode = true;
  3174. }
  3175. /**
  3176. * This method is overwritten since the node type is inferred from the operator
  3177. * and the input node types.
  3178. *
  3179. * @param {NodeBuilder} builder - The current node builder.
  3180. * @param {String} output - The current output string.
  3181. * @return {String} The node type.
  3182. */
  3183. getNodeType( builder, output ) {
  3184. const op = this.op;
  3185. const aNode = this.aNode;
  3186. const bNode = this.bNode;
  3187. const typeA = aNode.getNodeType( builder );
  3188. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3189. if ( typeA === 'void' || typeB === 'void' ) {
  3190. return 'void';
  3191. } else if ( op === '%' ) {
  3192. return typeA;
  3193. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3194. return builder.getIntegerType( typeA );
  3195. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3196. return 'bool';
  3197. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3198. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3199. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3200. } else {
  3201. // Handle matrix operations
  3202. if ( builder.isMatrix( typeA ) ) {
  3203. if ( typeB === 'float' ) {
  3204. return typeA; // matrix * scalar = matrix
  3205. } else if ( builder.isVector( typeB ) ) {
  3206. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3207. } else if ( builder.isMatrix( typeB ) ) {
  3208. return typeA; // matrix * matrix
  3209. }
  3210. } else if ( builder.isMatrix( typeB ) ) {
  3211. if ( typeA === 'float' ) {
  3212. return typeB; // scalar * matrix = matrix
  3213. } else if ( builder.isVector( typeA ) ) {
  3214. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3215. }
  3216. }
  3217. // Handle non-matrix cases
  3218. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3219. // anytype x anytype: use the greater length vector
  3220. return typeB;
  3221. }
  3222. return typeA;
  3223. }
  3224. }
  3225. generate( builder, output ) {
  3226. const op = this.op;
  3227. const aNode = this.aNode;
  3228. const bNode = this.bNode;
  3229. const type = this.getNodeType( builder, output );
  3230. let typeA = null;
  3231. let typeB = null;
  3232. if ( type !== 'void' ) {
  3233. typeA = aNode.getNodeType( builder );
  3234. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3235. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3236. if ( builder.isVector( typeA ) ) {
  3237. typeB = typeA;
  3238. } else if ( typeA !== typeB ) {
  3239. typeA = typeB = 'float';
  3240. }
  3241. } else if ( op === '>>' || op === '<<' ) {
  3242. typeA = type;
  3243. typeB = builder.changeComponentType( typeB, 'uint' );
  3244. } else if ( builder.isMatrix( typeA ) ) {
  3245. if ( typeB === 'float' ) {
  3246. // Keep matrix type for typeA, but ensure typeB stays float
  3247. typeB = 'float';
  3248. } else if ( builder.isVector( typeB ) ) {
  3249. // matrix x vector
  3250. typeB = builder.getVectorFromMatrix( typeA );
  3251. } else if ( builder.isMatrix( typeB ) ) ; else {
  3252. typeA = typeB = type;
  3253. }
  3254. } else if ( builder.isMatrix( typeB ) ) {
  3255. if ( typeA === 'float' ) {
  3256. // Keep matrix type for typeB, but ensure typeA stays float
  3257. typeA = 'float';
  3258. } else if ( builder.isVector( typeA ) ) {
  3259. // vector x matrix
  3260. typeA = builder.getVectorFromMatrix( typeB );
  3261. } else {
  3262. typeA = typeB = type;
  3263. }
  3264. } else {
  3265. // anytype x anytype
  3266. typeA = typeB = type;
  3267. }
  3268. } else {
  3269. typeA = typeB = type;
  3270. }
  3271. const a = aNode.build( builder, typeA );
  3272. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3273. const outputLength = builder.getTypeLength( output );
  3274. const fnOpSnippet = builder.getFunctionOperator( op );
  3275. if ( output !== 'void' ) {
  3276. if ( op === '<' && outputLength > 1 ) {
  3277. if ( builder.useComparisonMethod ) {
  3278. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3279. } else {
  3280. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3281. }
  3282. } else if ( op === '<=' && outputLength > 1 ) {
  3283. if ( builder.useComparisonMethod ) {
  3284. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3285. } else {
  3286. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3287. }
  3288. } else if ( op === '>' && outputLength > 1 ) {
  3289. if ( builder.useComparisonMethod ) {
  3290. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3291. } else {
  3292. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3293. }
  3294. } else if ( op === '>=' && outputLength > 1 ) {
  3295. if ( builder.useComparisonMethod ) {
  3296. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3297. } else {
  3298. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3299. }
  3300. } else if ( op === '!' || op === '~' ) {
  3301. return builder.format( `(${op}${a})`, typeA, output );
  3302. } else if ( fnOpSnippet ) {
  3303. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3304. } else {
  3305. // Handle matrix operations
  3306. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3307. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3308. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3309. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3310. } else {
  3311. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3312. }
  3313. }
  3314. } else if ( typeA !== 'void' ) {
  3315. if ( fnOpSnippet ) {
  3316. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3317. } else {
  3318. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3319. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3320. } else {
  3321. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3322. }
  3323. }
  3324. }
  3325. }
  3326. serialize( data ) {
  3327. super.serialize( data );
  3328. data.op = this.op;
  3329. }
  3330. deserialize( data ) {
  3331. super.deserialize( data );
  3332. this.op = data.op;
  3333. }
  3334. }
  3335. /**
  3336. * Returns the addition of two or more value.
  3337. *
  3338. * @function
  3339. * @param {Node} aNode - The first input.
  3340. * @param {Node} bNode - The second input.
  3341. * @param {...Node} params - Additional input parameters.
  3342. * @returns {OperatorNode}
  3343. */
  3344. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3345. /**
  3346. * Returns the subtraction of two or more value.
  3347. *
  3348. * @function
  3349. * @param {Node} aNode - The first input.
  3350. * @param {Node} bNode - The second input.
  3351. * @param {...Node} params - Additional input parameters.
  3352. * @returns {OperatorNode}
  3353. */
  3354. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3355. /**
  3356. * Returns the multiplication of two or more value.
  3357. *
  3358. * @function
  3359. * @param {Node} aNode - The first input.
  3360. * @param {Node} bNode - The second input.
  3361. * @param {...Node} params - Additional input parameters.
  3362. * @returns {OperatorNode}
  3363. */
  3364. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3365. /**
  3366. * Returns the division of two or more value.
  3367. *
  3368. * @function
  3369. * @param {Node} aNode - The first input.
  3370. * @param {Node} bNode - The second input.
  3371. * @param {...Node} params - Additional input parameters.
  3372. * @returns {OperatorNode}
  3373. */
  3374. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3375. /**
  3376. * Computes the remainder of dividing the first node by the second, for integer values.
  3377. *
  3378. * @function
  3379. * @param {Node} aNode - The first input.
  3380. * @param {Node} bNode - The second input.
  3381. * @returns {OperatorNode}
  3382. */
  3383. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3384. /**
  3385. * Checks if two nodes are equal.
  3386. *
  3387. * @function
  3388. * @param {Node} aNode - The first input.
  3389. * @param {Node} bNode - The second input.
  3390. * @returns {OperatorNode}
  3391. */
  3392. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3393. /**
  3394. * Checks if two nodes are not equal.
  3395. *
  3396. * @function
  3397. * @param {Node} aNode - The first input.
  3398. * @param {Node} bNode - The second input.
  3399. * @returns {OperatorNode}
  3400. */
  3401. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3402. /**
  3403. * Checks if the first node is less than the second.
  3404. *
  3405. * @function
  3406. * @param {Node} aNode - The first input.
  3407. * @param {Node} bNode - The second input.
  3408. * @returns {OperatorNode}
  3409. */
  3410. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3411. /**
  3412. * Checks if the first node is greater than the second.
  3413. *
  3414. * @function
  3415. * @param {Node} aNode - The first input.
  3416. * @param {Node} bNode - The second input.
  3417. * @returns {OperatorNode}
  3418. */
  3419. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3420. /**
  3421. * Checks if the first node is less than or equal to the second.
  3422. *
  3423. * @function
  3424. * @param {Node} aNode - The first input.
  3425. * @param {Node} bNode - The second input.
  3426. * @returns {OperatorNode}
  3427. */
  3428. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3429. /**
  3430. * Checks if the first node is greater than or equal to the second.
  3431. *
  3432. * @function
  3433. * @param {Node} aNode - The first input.
  3434. * @param {Node} bNode - The second input.
  3435. * @returns {OperatorNode}
  3436. */
  3437. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3438. /**
  3439. * Performs logical AND 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 and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3447. /**
  3448. * Performs logical OR on two nodes.
  3449. *
  3450. * @function
  3451. * @param {Node} aNode - The first input.
  3452. * @param {Node} bNode - The second input.
  3453. * @returns {OperatorNode}
  3454. */
  3455. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3456. /**
  3457. * Performs logical NOT on a node.
  3458. *
  3459. * @function
  3460. * @param {Node} aNode - The first input.
  3461. * @param {Node} bNode - The second input.
  3462. * @returns {OperatorNode}
  3463. */
  3464. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3465. /**
  3466. * Performs logical XOR on two nodes.
  3467. *
  3468. * @function
  3469. * @param {Node} aNode - The first input.
  3470. * @param {Node} bNode - The second input.
  3471. * @returns {OperatorNode}
  3472. */
  3473. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3474. /**
  3475. * Performs bitwise AND on two nodes.
  3476. *
  3477. * @function
  3478. * @param {Node} aNode - The first input.
  3479. * @param {Node} bNode - The second input.
  3480. * @returns {OperatorNode}
  3481. */
  3482. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3483. /**
  3484. * Performs bitwise NOT on a node.
  3485. *
  3486. * @function
  3487. * @param {Node} aNode - The first input.
  3488. * @param {Node} bNode - The second input.
  3489. * @returns {OperatorNode}
  3490. */
  3491. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3492. /**
  3493. * Performs bitwise OR on two nodes.
  3494. *
  3495. * @function
  3496. * @param {Node} aNode - The first input.
  3497. * @param {Node} bNode - The second input.
  3498. * @returns {OperatorNode}
  3499. */
  3500. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3501. /**
  3502. * Performs bitwise XOR on two nodes.
  3503. *
  3504. * @function
  3505. * @param {Node} aNode - The first input.
  3506. * @param {Node} bNode - The second input.
  3507. * @returns {OperatorNode}
  3508. */
  3509. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3510. /**
  3511. * Shifts a node to the left.
  3512. *
  3513. * @function
  3514. * @param {Node} aNode - The node to shift.
  3515. * @param {Node} bNode - The value to shift.
  3516. * @returns {OperatorNode}
  3517. */
  3518. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3519. /**
  3520. * Shifts a node to the right.
  3521. *
  3522. * @function
  3523. * @param {Node} aNode - The node to shift.
  3524. * @param {Node} bNode - The value to shift.
  3525. * @returns {OperatorNode}
  3526. */
  3527. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3528. addMethodChaining( 'add', add );
  3529. addMethodChaining( 'sub', sub );
  3530. addMethodChaining( 'mul', mul );
  3531. addMethodChaining( 'div', div );
  3532. addMethodChaining( 'modInt', modInt );
  3533. addMethodChaining( 'equal', equal );
  3534. addMethodChaining( 'notEqual', notEqual );
  3535. addMethodChaining( 'lessThan', lessThan );
  3536. addMethodChaining( 'greaterThan', greaterThan );
  3537. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3538. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3539. addMethodChaining( 'and', and );
  3540. addMethodChaining( 'or', or );
  3541. addMethodChaining( 'not', not );
  3542. addMethodChaining( 'xor', xor );
  3543. addMethodChaining( 'bitAnd', bitAnd );
  3544. addMethodChaining( 'bitNot', bitNot );
  3545. addMethodChaining( 'bitOr', bitOr );
  3546. addMethodChaining( 'bitXor', bitXor );
  3547. addMethodChaining( 'shiftLeft', shiftLeft );
  3548. addMethodChaining( 'shiftRight', shiftRight );
  3549. /**
  3550. * @function
  3551. * @deprecated since r168. Use {@link modInt} instead.
  3552. *
  3553. * @param {...any} params
  3554. * @returns {Function}
  3555. */
  3556. const remainder = ( ...params ) => { // @deprecated, r168
  3557. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3558. return modInt( ...params );
  3559. };
  3560. addMethodChaining( 'remainder', remainder );
  3561. /** @module MathNode **/
  3562. /**
  3563. * This node represents a variety of mathematical methods available in shaders.
  3564. * They are divided into three categories:
  3565. *
  3566. * - Methods with one input like `sin`, `cos` or `normalize`.
  3567. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3568. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3569. *
  3570. * @augments TempNode
  3571. */
  3572. class MathNode extends TempNode {
  3573. static get type() {
  3574. return 'MathNode';
  3575. }
  3576. /**
  3577. * Constructs a new math node.
  3578. *
  3579. * @param {String} method - The method name.
  3580. * @param {Node} aNode - The first input.
  3581. * @param {Node?} [bNode=null] - The second input.
  3582. * @param {Node?} [cNode=null] - The third input.
  3583. */
  3584. constructor( method, aNode, bNode = null, cNode = null ) {
  3585. super();
  3586. /**
  3587. * The method name.
  3588. *
  3589. * @type {String}
  3590. */
  3591. this.method = method;
  3592. /**
  3593. * The first input.
  3594. *
  3595. * @type {Node}
  3596. */
  3597. this.aNode = aNode;
  3598. /**
  3599. * The second input.
  3600. *
  3601. * @type {Node?}
  3602. * @default null
  3603. */
  3604. this.bNode = bNode;
  3605. /**
  3606. * The third input.
  3607. *
  3608. * @type {Node?}
  3609. * @default null
  3610. */
  3611. this.cNode = cNode;
  3612. /**
  3613. * This flag can be used for type testing.
  3614. *
  3615. * @type {Boolean}
  3616. * @readonly
  3617. * @default true
  3618. */
  3619. this.isMathNode = true;
  3620. }
  3621. /**
  3622. * The input type is inferred from the node types of the input nodes.
  3623. *
  3624. * @param {NodeBuilder} builder - The current node builder.
  3625. * @return {String} The input type.
  3626. */
  3627. getInputType( builder ) {
  3628. const aType = this.aNode.getNodeType( builder );
  3629. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3630. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3631. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3632. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3633. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3634. if ( aLen > bLen && aLen > cLen ) {
  3635. return aType;
  3636. } else if ( bLen > cLen ) {
  3637. return bType;
  3638. } else if ( cLen > aLen ) {
  3639. return cType;
  3640. }
  3641. return aType;
  3642. }
  3643. /**
  3644. * The selected method as well as the input type determine the node type of this node.
  3645. *
  3646. * @param {NodeBuilder} builder - The current node builder.
  3647. * @return {String} The node type.
  3648. */
  3649. getNodeType( builder ) {
  3650. const method = this.method;
  3651. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3652. return 'float';
  3653. } else if ( method === MathNode.CROSS ) {
  3654. return 'vec3';
  3655. } else if ( method === MathNode.ALL ) {
  3656. return 'bool';
  3657. } else if ( method === MathNode.EQUALS ) {
  3658. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3659. } else if ( method === MathNode.MOD ) {
  3660. return this.aNode.getNodeType( builder );
  3661. } else {
  3662. return this.getInputType( builder );
  3663. }
  3664. }
  3665. generate( builder, output ) {
  3666. let method = this.method;
  3667. const type = this.getNodeType( builder );
  3668. const inputType = this.getInputType( builder );
  3669. const a = this.aNode;
  3670. const b = this.bNode;
  3671. const c = this.cNode;
  3672. const coordinateSystem = builder.renderer.coordinateSystem;
  3673. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3674. // dir can be either a direction vector or a normal vector
  3675. // upper-left 3x3 of matrix is assumed to be orthogonal
  3676. let tA = a;
  3677. let tB = b;
  3678. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3679. tB = vec4( vec3( tB ), 0.0 );
  3680. } else {
  3681. tA = vec4( vec3( tA ), 0.0 );
  3682. }
  3683. const mulNode = mul( tA, tB ).xyz;
  3684. return normalize( mulNode ).build( builder, output );
  3685. } else if ( method === MathNode.NEGATE ) {
  3686. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3687. } else if ( method === MathNode.ONE_MINUS ) {
  3688. return sub( 1.0, a ).build( builder, output );
  3689. } else if ( method === MathNode.RECIPROCAL ) {
  3690. return div( 1.0, a ).build( builder, output );
  3691. } else if ( method === MathNode.DIFFERENCE ) {
  3692. return abs( sub( a, b ) ).build( builder, output );
  3693. } else {
  3694. const params = [];
  3695. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3696. params.push(
  3697. a.build( builder, type ),
  3698. b.build( builder, type )
  3699. );
  3700. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3701. params.push(
  3702. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3703. b.build( builder, inputType )
  3704. );
  3705. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3706. params.push(
  3707. a.build( builder, inputType ),
  3708. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3709. );
  3710. } else if ( method === MathNode.REFRACT ) {
  3711. params.push(
  3712. a.build( builder, inputType ),
  3713. b.build( builder, inputType ),
  3714. c.build( builder, 'float' )
  3715. );
  3716. } else if ( method === MathNode.MIX ) {
  3717. params.push(
  3718. a.build( builder, inputType ),
  3719. b.build( builder, inputType ),
  3720. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3721. );
  3722. } else {
  3723. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3724. method = 'atan2';
  3725. }
  3726. params.push( a.build( builder, inputType ) );
  3727. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3728. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3729. }
  3730. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3731. }
  3732. }
  3733. serialize( data ) {
  3734. super.serialize( data );
  3735. data.method = this.method;
  3736. }
  3737. deserialize( data ) {
  3738. super.deserialize( data );
  3739. this.method = data.method;
  3740. }
  3741. }
  3742. // 1 input
  3743. MathNode.ALL = 'all';
  3744. MathNode.ANY = 'any';
  3745. MathNode.RADIANS = 'radians';
  3746. MathNode.DEGREES = 'degrees';
  3747. MathNode.EXP = 'exp';
  3748. MathNode.EXP2 = 'exp2';
  3749. MathNode.LOG = 'log';
  3750. MathNode.LOG2 = 'log2';
  3751. MathNode.SQRT = 'sqrt';
  3752. MathNode.INVERSE_SQRT = 'inversesqrt';
  3753. MathNode.FLOOR = 'floor';
  3754. MathNode.CEIL = 'ceil';
  3755. MathNode.NORMALIZE = 'normalize';
  3756. MathNode.FRACT = 'fract';
  3757. MathNode.SIN = 'sin';
  3758. MathNode.COS = 'cos';
  3759. MathNode.TAN = 'tan';
  3760. MathNode.ASIN = 'asin';
  3761. MathNode.ACOS = 'acos';
  3762. MathNode.ATAN = 'atan';
  3763. MathNode.ABS = 'abs';
  3764. MathNode.SIGN = 'sign';
  3765. MathNode.LENGTH = 'length';
  3766. MathNode.NEGATE = 'negate';
  3767. MathNode.ONE_MINUS = 'oneMinus';
  3768. MathNode.DFDX = 'dFdx';
  3769. MathNode.DFDY = 'dFdy';
  3770. MathNode.ROUND = 'round';
  3771. MathNode.RECIPROCAL = 'reciprocal';
  3772. MathNode.TRUNC = 'trunc';
  3773. MathNode.FWIDTH = 'fwidth';
  3774. MathNode.TRANSPOSE = 'transpose';
  3775. // 2 inputs
  3776. MathNode.BITCAST = 'bitcast';
  3777. MathNode.EQUALS = 'equals';
  3778. MathNode.MIN = 'min';
  3779. MathNode.MAX = 'max';
  3780. MathNode.MOD = 'mod';
  3781. MathNode.STEP = 'step';
  3782. MathNode.REFLECT = 'reflect';
  3783. MathNode.DISTANCE = 'distance';
  3784. MathNode.DIFFERENCE = 'difference';
  3785. MathNode.DOT = 'dot';
  3786. MathNode.CROSS = 'cross';
  3787. MathNode.POW = 'pow';
  3788. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3789. // 3 inputs
  3790. MathNode.MIX = 'mix';
  3791. MathNode.CLAMP = 'clamp';
  3792. MathNode.REFRACT = 'refract';
  3793. MathNode.SMOOTHSTEP = 'smoothstep';
  3794. MathNode.FACEFORWARD = 'faceforward';
  3795. // 1 inputs
  3796. /**
  3797. * A small value used to handle floating-point precision errors.
  3798. *
  3799. * @type {Node<float>}
  3800. */
  3801. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3802. /**
  3803. * Represents infinity.
  3804. *
  3805. * @type {Node<float>}
  3806. */
  3807. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3808. /**
  3809. * Represents PI.
  3810. *
  3811. * @type {Node<float>}
  3812. */
  3813. const PI = /*@__PURE__*/ float( Math.PI );
  3814. /**
  3815. * Represents PI * 2.
  3816. *
  3817. * @type {Node<float>}
  3818. */
  3819. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3820. /**
  3821. * Returns `true` if all components of `x` are `true`.
  3822. *
  3823. * @function
  3824. * @param {Node | Number} x - The parameter.
  3825. * @returns {Node<bool>}
  3826. */
  3827. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3828. /**
  3829. * Returns `true` if any components of `x` are `true`.
  3830. *
  3831. * @function
  3832. * @param {Node | Number} x - The parameter.
  3833. * @returns {Node<bool>}
  3834. */
  3835. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3836. /**
  3837. * Converts a quantity in degrees to radians.
  3838. *
  3839. * @function
  3840. * @param {Node | Number} x - The input in degrees.
  3841. * @returns {Node}
  3842. */
  3843. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3844. /**
  3845. * Convert a quantity in radians to degrees.
  3846. *
  3847. * @function
  3848. * @param {Node | Number} x - The input in radians.
  3849. * @returns {Node}
  3850. */
  3851. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3852. /**
  3853. * Returns the natural exponentiation of the parameter.
  3854. *
  3855. * @function
  3856. * @param {Node | Number} x - The parameter.
  3857. * @returns {Node}
  3858. */
  3859. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3860. /**
  3861. * Returns 2 raised to the power of the parameter.
  3862. *
  3863. * @function
  3864. * @param {Node | Number} x - The parameter.
  3865. * @returns {Node}
  3866. */
  3867. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3868. /**
  3869. * Returns the natural logarithm of the parameter.
  3870. *
  3871. * @function
  3872. * @param {Node | Number} x - The parameter.
  3873. * @returns {Node}
  3874. */
  3875. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3876. /**
  3877. * Returns the base 2 logarithm of the parameter.
  3878. *
  3879. * @function
  3880. * @param {Node | Number} x - The parameter.
  3881. * @returns {Node}
  3882. */
  3883. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3884. /**
  3885. * Returns the square root of the parameter.
  3886. *
  3887. * @function
  3888. * @param {Node | Number} x - The parameter.
  3889. * @returns {Node}
  3890. */
  3891. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3892. /**
  3893. * Returns the inverse of the square root of the parameter.
  3894. *
  3895. * @function
  3896. * @param {Node | Number} x - The parameter.
  3897. * @returns {Node}
  3898. */
  3899. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3900. /**
  3901. * Finds the nearest integer less than or equal to the parameter.
  3902. *
  3903. * @function
  3904. * @param {Node | Number} x - The parameter.
  3905. * @returns {Node}
  3906. */
  3907. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3908. /**
  3909. * Finds the nearest integer that is greater than or equal to the parameter.
  3910. *
  3911. * @function
  3912. * @param {Node | Number} x - The parameter.
  3913. * @returns {Node}
  3914. */
  3915. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3916. /**
  3917. * Calculates the unit vector in the same direction as the original vector.
  3918. *
  3919. * @function
  3920. * @param {Node} x - The input vector.
  3921. * @returns {Node}
  3922. */
  3923. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3924. /**
  3925. * Computes the fractional part of the parameter.
  3926. *
  3927. * @function
  3928. * @param {Node | Number} x - The parameter.
  3929. * @returns {Node}
  3930. */
  3931. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3932. /**
  3933. * Returns the sine of the parameter.
  3934. *
  3935. * @function
  3936. * @param {Node | Number} x - The parameter.
  3937. * @returns {Node}
  3938. */
  3939. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3940. /**
  3941. * Returns the cosine of the parameter.
  3942. *
  3943. * @function
  3944. * @param {Node | Number} x - The parameter.
  3945. * @returns {Node}
  3946. */
  3947. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3948. /**
  3949. * Returns the tangent of the parameter.
  3950. *
  3951. * @function
  3952. * @param {Node | Number} x - The parameter.
  3953. * @returns {Node}
  3954. */
  3955. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3956. /**
  3957. * Returns the arcsine of the parameter.
  3958. *
  3959. * @function
  3960. * @param {Node | Number} x - The parameter.
  3961. * @returns {Node}
  3962. */
  3963. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3964. /**
  3965. * Returns the arccosine of the parameter.
  3966. *
  3967. * @function
  3968. * @param {Node | Number} x - The parameter.
  3969. * @returns {Node}
  3970. */
  3971. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3972. /**
  3973. * Returns the arc-tangent of the parameter.
  3974. * If two parameters are provided, the result is `atan2(y/x)`.
  3975. *
  3976. * @function
  3977. * @param {Node | Number} y - The y parameter.
  3978. * @param {(Node | Number)?} x - The x parameter.
  3979. * @returns {Node}
  3980. */
  3981. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3982. /**
  3983. * Returns the absolute value of the parameter.
  3984. *
  3985. * @function
  3986. * @param {Node | Number} x - The parameter.
  3987. * @returns {Node}
  3988. */
  3989. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3990. /**
  3991. * Extracts the sign of the parameter.
  3992. *
  3993. * @function
  3994. * @param {Node | Number} x - The parameter.
  3995. * @returns {Node}
  3996. */
  3997. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3998. /**
  3999. * Calculates the length of a vector.
  4000. *
  4001. * @function
  4002. * @param {Node} x - The parameter.
  4003. * @returns {Node<float>}
  4004. */
  4005. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  4006. /**
  4007. * Negates the value of the parameter (-x).
  4008. *
  4009. * @function
  4010. * @param {Node | Number} x - The parameter.
  4011. * @returns {Node}
  4012. */
  4013. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  4014. /**
  4015. * Return `1` minus the parameter.
  4016. *
  4017. * @function
  4018. * @param {Node | Number} x - The parameter.
  4019. * @returns {Node}
  4020. */
  4021. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  4022. /**
  4023. * Returns the partial derivative of the parameter with respect to x.
  4024. *
  4025. * @function
  4026. * @param {Node | Number} x - The parameter.
  4027. * @returns {Node}
  4028. */
  4029. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  4030. /**
  4031. * Returns the partial derivative of the parameter with respect to y.
  4032. *
  4033. * @function
  4034. * @param {Node | Number} x - The parameter.
  4035. * @returns {Node}
  4036. */
  4037. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  4038. /**
  4039. * Rounds the parameter to the nearest integer.
  4040. *
  4041. * @function
  4042. * @param {Node | Number} x - The parameter.
  4043. * @returns {Node}
  4044. */
  4045. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  4046. /**
  4047. * Returns the reciprocal of the parameter `(1/x)`.
  4048. *
  4049. * @function
  4050. * @param {Node | Number} x - The parameter.
  4051. * @returns {Node}
  4052. */
  4053. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  4054. /**
  4055. * Truncates the parameter, removing the fractional part.
  4056. *
  4057. * @function
  4058. * @param {Node | Number} x - The parameter.
  4059. * @returns {Node}
  4060. */
  4061. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  4062. /**
  4063. * Returns the sum of the absolute derivatives in x and y.
  4064. *
  4065. * @function
  4066. * @param {Node | Number} x - The parameter.
  4067. * @returns {Node}
  4068. */
  4069. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  4070. /**
  4071. * Returns the transpose of a matrix.
  4072. *
  4073. * @function
  4074. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4075. * @returns {Node}
  4076. */
  4077. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  4078. // 2 inputs
  4079. /**
  4080. * Reinterpret the bit representation of a value in one type as a value in another type.
  4081. *
  4082. * @function
  4083. * @param {Node | Number} x - The parameter.
  4084. * @param {String} y - The new type.
  4085. * @returns {Node}
  4086. */
  4087. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  4088. /**
  4089. * Returns `true` if `x` equals `y`.
  4090. *
  4091. * @function
  4092. * @param {Node | Number} x - The first parameter.
  4093. * @param {Node | Number} y - The second parameter.
  4094. * @returns {Node<bool>}
  4095. */
  4096. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  4097. /**
  4098. * Returns the lesser of two values.
  4099. *
  4100. * @function
  4101. * @param {Node | Number} x - The y parameter.
  4102. * @param {Node | Number} y - The x parameter.
  4103. * @returns {Node}
  4104. */
  4105. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  4106. /**
  4107. * Returns the greater of two values.
  4108. *
  4109. * @function
  4110. * @param {Node | Number} x - The y parameter.
  4111. * @param {Node | Number} y - The x parameter.
  4112. * @returns {Node}
  4113. */
  4114. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  4115. /**
  4116. * Computes the remainder of dividing the first node by the second one.
  4117. *
  4118. * @function
  4119. * @param {Node | Number} x - The y parameter.
  4120. * @param {Node | Number} y - The x parameter.
  4121. * @returns {Node}
  4122. */
  4123. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  4124. /**
  4125. * Generate a step function by comparing two values.
  4126. *
  4127. * @function
  4128. * @param {Node | Number} x - The y parameter.
  4129. * @param {Node | Number} y - The x parameter.
  4130. * @returns {Node}
  4131. */
  4132. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  4133. /**
  4134. * Calculates the reflection direction for an incident vector.
  4135. *
  4136. * @function
  4137. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4138. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4139. * @returns {Node<vec2|vec3|vec4>}
  4140. */
  4141. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  4142. /**
  4143. * Calculates the distance between two points.
  4144. *
  4145. * @function
  4146. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4147. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4148. * @returns {Node<float>}
  4149. */
  4150. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  4151. /**
  4152. * Calculates the absolute difference between two values.
  4153. *
  4154. * @function
  4155. * @param {Node | Number} x - The first parameter.
  4156. * @param {Node | Number} y - The second parameter.
  4157. * @returns {Node}
  4158. */
  4159. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  4160. /**
  4161. * Calculates the dot product of two vectors.
  4162. *
  4163. * @function
  4164. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4165. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4166. * @returns {Node<float>}
  4167. */
  4168. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  4169. /**
  4170. * Calculates the cross product of two vectors.
  4171. *
  4172. * @function
  4173. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4174. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4175. * @returns {Node<vec2|vec3|vec4>}
  4176. */
  4177. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  4178. /**
  4179. * Return the value of the first parameter raised to the power of the second one.
  4180. *
  4181. * @function
  4182. * @param {Node | Number} x - The first parameter.
  4183. * @param {Node | Number} y - The second parameter.
  4184. * @returns {Node}
  4185. */
  4186. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  4187. /**
  4188. * Returns the square of the parameter.
  4189. *
  4190. * @function
  4191. * @param {Node | Number} x - The first parameter.
  4192. * @returns {Node}
  4193. */
  4194. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4195. /**
  4196. * Returns the cube of the parameter.
  4197. *
  4198. * @function
  4199. * @param {Node | Number} x - The first parameter.
  4200. * @returns {Node}
  4201. */
  4202. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4203. /**
  4204. * Returns the fourth power of the parameter.
  4205. *
  4206. * @function
  4207. * @param {Node | Number} x - The first parameter.
  4208. * @returns {Node}
  4209. */
  4210. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4211. /**
  4212. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4213. *
  4214. * @function
  4215. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4216. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4217. * @returns {Node}
  4218. */
  4219. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4220. /**
  4221. * Returns the cube root of a number.
  4222. *
  4223. * @function
  4224. * @param {Node | Number} a - The first parameter.
  4225. * @returns {Node}
  4226. */
  4227. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4228. /**
  4229. * Calculate the squared length of a vector.
  4230. *
  4231. * @function
  4232. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4233. * @returns {Node<float>}
  4234. */
  4235. const lengthSq = ( a ) => dot( a, a );
  4236. /**
  4237. * Linearly interpolates between two values.
  4238. *
  4239. * @function
  4240. * @param {Node | Number} a - The first parameter.
  4241. * @param {Node | Number} b - The second parameter.
  4242. * @param {Node | Number} t - The interpolation value.
  4243. * @returns {Node}
  4244. */
  4245. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4246. /**
  4247. * Constrains a value to lie between two further values.
  4248. *
  4249. * @function
  4250. * @param {Node | Number} value - The value to constrain.
  4251. * @param {Node | Number} [low=0] - The lower bound.
  4252. * @param {Node | Number} [high=1] - The upper bound.
  4253. * @returns {Node}
  4254. */
  4255. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4256. /**
  4257. * Constrains a value between `0` and `1`.
  4258. *
  4259. * @function
  4260. * @param {Node | Number} value - The value to constrain.
  4261. * @returns {Node}
  4262. */
  4263. const saturate = ( value ) => clamp( value );
  4264. /**
  4265. * Calculates the refraction direction for an incident vector.
  4266. *
  4267. * @function
  4268. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4269. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4270. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4271. * @returns {Node<vec2|vec3|vec4>}
  4272. */
  4273. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4274. /**
  4275. * Performs a Hermite interpolation between two values.
  4276. *
  4277. * @function
  4278. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4279. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4280. * @param {Node | Number} x - The source value for interpolation.
  4281. * @returns {Node}
  4282. */
  4283. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4284. /**
  4285. * Returns a vector pointing in the same direction as another.
  4286. *
  4287. * @function
  4288. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4289. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4290. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4291. * @returns {Node<vec2|vec3|vec4>}
  4292. */
  4293. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4294. /**
  4295. * Returns a random value for the given uv.
  4296. *
  4297. * @function
  4298. * @param {Node<vec2>} uv - The uv node.
  4299. * @returns {Node<float>}
  4300. */
  4301. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4302. const a = 12.9898, b = 78.233, c = 43758.5453;
  4303. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4304. return fract( sin( sn ).mul( c ) );
  4305. } );
  4306. /**
  4307. * Alias for `mix()` with a different parameter order.
  4308. *
  4309. * @function
  4310. * @param {Node | Number} t - The interpolation value.
  4311. * @param {Node | Number} e1 - The first parameter.
  4312. * @param {Node | Number} e2 - The second parameter.
  4313. * @returns {Node}
  4314. */
  4315. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4316. /**
  4317. * Alias for `smoothstep()` with a different parameter order.
  4318. *
  4319. * @function
  4320. * @param {Node | Number} x - The source value for interpolation.
  4321. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4322. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4323. * @returns {Node}
  4324. */
  4325. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4326. /**
  4327. * Returns the arc-tangent of the quotient of its parameters.
  4328. *
  4329. * @function
  4330. * @deprecated since r172. Use {@link atan} instead.
  4331. *
  4332. * @param {Node | Number} y - The y parameter.
  4333. * @param {Node | Number} x - The x parameter.
  4334. * @returns {Node}
  4335. */
  4336. const atan2 = ( y, x ) => { // @deprecated, r172
  4337. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4338. return atan( y, x );
  4339. };
  4340. // GLSL alias function
  4341. const faceforward = faceForward;
  4342. const inversesqrt = inverseSqrt;
  4343. // Method chaining
  4344. addMethodChaining( 'all', all );
  4345. addMethodChaining( 'any', any );
  4346. addMethodChaining( 'equals', equals );
  4347. addMethodChaining( 'radians', radians );
  4348. addMethodChaining( 'degrees', degrees );
  4349. addMethodChaining( 'exp', exp );
  4350. addMethodChaining( 'exp2', exp2 );
  4351. addMethodChaining( 'log', log );
  4352. addMethodChaining( 'log2', log2 );
  4353. addMethodChaining( 'sqrt', sqrt );
  4354. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4355. addMethodChaining( 'floor', floor );
  4356. addMethodChaining( 'ceil', ceil );
  4357. addMethodChaining( 'normalize', normalize );
  4358. addMethodChaining( 'fract', fract );
  4359. addMethodChaining( 'sin', sin );
  4360. addMethodChaining( 'cos', cos );
  4361. addMethodChaining( 'tan', tan );
  4362. addMethodChaining( 'asin', asin );
  4363. addMethodChaining( 'acos', acos );
  4364. addMethodChaining( 'atan', atan );
  4365. addMethodChaining( 'abs', abs );
  4366. addMethodChaining( 'sign', sign );
  4367. addMethodChaining( 'length', length );
  4368. addMethodChaining( 'lengthSq', lengthSq );
  4369. addMethodChaining( 'negate', negate );
  4370. addMethodChaining( 'oneMinus', oneMinus );
  4371. addMethodChaining( 'dFdx', dFdx );
  4372. addMethodChaining( 'dFdy', dFdy );
  4373. addMethodChaining( 'round', round );
  4374. addMethodChaining( 'reciprocal', reciprocal );
  4375. addMethodChaining( 'trunc', trunc );
  4376. addMethodChaining( 'fwidth', fwidth );
  4377. addMethodChaining( 'atan2', atan2 );
  4378. addMethodChaining( 'min', min$1 );
  4379. addMethodChaining( 'max', max$1 );
  4380. addMethodChaining( 'mod', mod );
  4381. addMethodChaining( 'step', step );
  4382. addMethodChaining( 'reflect', reflect );
  4383. addMethodChaining( 'distance', distance );
  4384. addMethodChaining( 'dot', dot );
  4385. addMethodChaining( 'cross', cross );
  4386. addMethodChaining( 'pow', pow );
  4387. addMethodChaining( 'pow2', pow2 );
  4388. addMethodChaining( 'pow3', pow3 );
  4389. addMethodChaining( 'pow4', pow4 );
  4390. addMethodChaining( 'transformDirection', transformDirection );
  4391. addMethodChaining( 'mix', mixElement );
  4392. addMethodChaining( 'clamp', clamp );
  4393. addMethodChaining( 'refract', refract );
  4394. addMethodChaining( 'smoothstep', smoothstepElement );
  4395. addMethodChaining( 'faceForward', faceForward );
  4396. addMethodChaining( 'difference', difference );
  4397. addMethodChaining( 'saturate', saturate );
  4398. addMethodChaining( 'cbrt', cbrt );
  4399. addMethodChaining( 'transpose', transpose );
  4400. addMethodChaining( 'rand', rand );
  4401. /** @module ConditionalNode **/
  4402. /**
  4403. * Represents a logical `if/else` statement. Can be used as an alternative
  4404. * to the `If()`/`Else()` syntax.
  4405. *
  4406. * The corresponding TSL `select()` looks like so:
  4407. * ```js
  4408. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4409. * ```
  4410. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4411. * determine the outcome of the entire statement.
  4412. *
  4413. * @augments Node
  4414. */
  4415. class ConditionalNode extends Node {
  4416. static get type() {
  4417. return 'ConditionalNode';
  4418. }
  4419. /**
  4420. * Constructs a new conditional node.
  4421. *
  4422. * @param {Node} condNode - The node that defines the condition.
  4423. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4424. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4425. */
  4426. constructor( condNode, ifNode, elseNode = null ) {
  4427. super();
  4428. /**
  4429. * The node that defines the condition.
  4430. *
  4431. * @type {Node}
  4432. */
  4433. this.condNode = condNode;
  4434. /**
  4435. * The node that is evaluate when the condition ends up `true`.
  4436. *
  4437. * @type {Node}
  4438. */
  4439. this.ifNode = ifNode;
  4440. /**
  4441. * The node that is evaluate when the condition ends up `false`.
  4442. *
  4443. * @type {Node?}
  4444. * @default null
  4445. */
  4446. this.elseNode = elseNode;
  4447. }
  4448. /**
  4449. * This method is overwritten since the node type is inferred from the if/else
  4450. * nodes.
  4451. *
  4452. * @param {NodeBuilder} builder - The current node builder.
  4453. * @return {String} The node type.
  4454. */
  4455. getNodeType( builder ) {
  4456. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4457. if ( ifNode === undefined ) {
  4458. // fallback setup
  4459. this.setup( builder );
  4460. return this.getNodeType( builder );
  4461. }
  4462. const ifType = ifNode.getNodeType( builder );
  4463. if ( elseNode !== null ) {
  4464. const elseType = elseNode.getNodeType( builder );
  4465. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4466. return elseType;
  4467. }
  4468. }
  4469. return ifType;
  4470. }
  4471. setup( builder ) {
  4472. const condNode = this.condNode.cache();
  4473. const ifNode = this.ifNode.cache();
  4474. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4475. //
  4476. const currentNodeBlock = builder.context.nodeBlock;
  4477. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4478. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4479. //
  4480. const properties = builder.getNodeProperties( this );
  4481. properties.condNode = condNode;
  4482. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4483. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4484. }
  4485. generate( builder, output ) {
  4486. const type = this.getNodeType( builder );
  4487. const nodeData = builder.getDataFromNode( this );
  4488. if ( nodeData.nodeProperty !== undefined ) {
  4489. return nodeData.nodeProperty;
  4490. }
  4491. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4492. const needsOutput = output !== 'void';
  4493. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4494. nodeData.nodeProperty = nodeProperty;
  4495. const nodeSnippet = condNode.build( builder, 'bool' );
  4496. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4497. let ifSnippet = ifNode.build( builder, type );
  4498. if ( ifSnippet ) {
  4499. if ( needsOutput ) {
  4500. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4501. } else {
  4502. ifSnippet = 'return ' + ifSnippet + ';';
  4503. }
  4504. }
  4505. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4506. if ( elseNode !== null ) {
  4507. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4508. let elseSnippet = elseNode.build( builder, type );
  4509. if ( elseSnippet ) {
  4510. if ( needsOutput ) {
  4511. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4512. } else {
  4513. elseSnippet = 'return ' + elseSnippet + ';';
  4514. }
  4515. }
  4516. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4517. } else {
  4518. builder.addFlowCode( '\n\n' );
  4519. }
  4520. return builder.format( nodeProperty, type, output );
  4521. }
  4522. }
  4523. /**
  4524. * TSL function for creating a conditional node.
  4525. *
  4526. * @function
  4527. * @param {Node} condNode - The node that defines the condition.
  4528. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4529. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4530. * @returns {ConditionalNode}
  4531. */
  4532. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4533. addMethodChaining( 'select', select );
  4534. // Deprecated
  4535. /**
  4536. * @function
  4537. * @deprecated since r168. Use {@link select} instead.
  4538. *
  4539. * @param {...any} params
  4540. * @returns {ConditionalNode}
  4541. */
  4542. const cond = ( ...params ) => { // @deprecated, r168
  4543. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4544. return select( ...params );
  4545. };
  4546. addMethodChaining( 'cond', cond );
  4547. /** @module ContextNode **/
  4548. /**
  4549. * This node can be used as a context management component for another node.
  4550. * {@link NodeBuilder} performs its node building process in a specific context and
  4551. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4552. *
  4553. * ```js
  4554. *node.context( { getUV: () => customCoord } );
  4555. *```
  4556. * @augments Node
  4557. */
  4558. class ContextNode extends Node {
  4559. static get type() {
  4560. return 'ContextNode';
  4561. }
  4562. /**
  4563. * Constructs a new context node.
  4564. *
  4565. * @param {Node} node - The node whose context should be modified.
  4566. * @param {Object} [value={}] - The modified context data.
  4567. */
  4568. constructor( node, value = {} ) {
  4569. super();
  4570. /**
  4571. * This flag can be used for type testing.
  4572. *
  4573. * @type {Boolean}
  4574. * @readonly
  4575. * @default true
  4576. */
  4577. this.isContextNode = true;
  4578. /**
  4579. * The node whose context should be modified.
  4580. *
  4581. * @type {Node}
  4582. */
  4583. this.node = node;
  4584. /**
  4585. * The modified context data.
  4586. *
  4587. * @type {Object}
  4588. * @default {}
  4589. */
  4590. this.value = value;
  4591. }
  4592. /**
  4593. * This method is overwritten to ensure it returns the reference to {@link module:ContextNode~ContextNode#node}.
  4594. *
  4595. * @return {Node} A reference to {@link module:ContextNode~ContextNode#node}.
  4596. */
  4597. getScope() {
  4598. return this.node.getScope();
  4599. }
  4600. /**
  4601. * This method is overwritten to ensure it returns the type of {@link module:ContextNode~ContextNode#node}.
  4602. *
  4603. * @param {NodeBuilder} builder - The current node builder.
  4604. * @return {String} The node type.
  4605. */
  4606. getNodeType( builder ) {
  4607. return this.node.getNodeType( builder );
  4608. }
  4609. analyze( builder ) {
  4610. this.node.build( builder );
  4611. }
  4612. setup( builder ) {
  4613. const previousContext = builder.getContext();
  4614. builder.setContext( { ...builder.context, ...this.value } );
  4615. const node = this.node.build( builder );
  4616. builder.setContext( previousContext );
  4617. return node;
  4618. }
  4619. generate( builder, output ) {
  4620. const previousContext = builder.getContext();
  4621. builder.setContext( { ...builder.context, ...this.value } );
  4622. const snippet = this.node.build( builder, output );
  4623. builder.setContext( previousContext );
  4624. return snippet;
  4625. }
  4626. }
  4627. /**
  4628. * TSL function for creating a context node.
  4629. *
  4630. * @function
  4631. * @param {Node} node - The node whose context should be modified.
  4632. * @param {Object} [value={}] - The modified context data.
  4633. * @returns {ContextNode}
  4634. */
  4635. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4636. /**
  4637. * TSL function for defining a label context value for a given node.
  4638. *
  4639. * @function
  4640. * @param {Node} node - The node whose context should be modified.
  4641. * @param {String} name - The name/label to set.
  4642. * @returns {ContextNode}
  4643. */
  4644. const label = ( node, name ) => context( node, { label: name } );
  4645. addMethodChaining( 'context', context );
  4646. addMethodChaining( 'label', label );
  4647. /** @module VarNode **/
  4648. /**
  4649. * Class for representing shader variables as nodes. Variables are created from
  4650. * existing nodes like the following:
  4651. *
  4652. * ```js
  4653. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4654. * ```
  4655. *
  4656. * @augments Node
  4657. */
  4658. class VarNode extends Node {
  4659. static get type() {
  4660. return 'VarNode';
  4661. }
  4662. /**
  4663. * Constructs a new variable node.
  4664. *
  4665. * @param {Node} node - The node for which a variable should be created.
  4666. * @param {String?} name - The name of the variable in the shader.
  4667. * @param {Boolean?} readOnly - The read-only flag.
  4668. */
  4669. constructor( node, name = null, readOnly = false ) {
  4670. super();
  4671. /**
  4672. * The node for which a variable should be created.
  4673. *
  4674. * @type {Node}
  4675. */
  4676. this.node = node;
  4677. /**
  4678. * The name of the variable in the shader. If no name is defined,
  4679. * the node system auto-generates one.
  4680. *
  4681. * @type {String?}
  4682. * @default null
  4683. */
  4684. this.name = name;
  4685. /**
  4686. * `VarNode` sets this property to `true` by default.
  4687. *
  4688. * @type {Boolean}
  4689. * @default true
  4690. */
  4691. this.global = true;
  4692. /**
  4693. * This flag can be used for type testing.
  4694. *
  4695. * @type {Boolean}
  4696. * @readonly
  4697. * @default true
  4698. */
  4699. this.isVarNode = true;
  4700. /**
  4701. *
  4702. * The read-only flag.
  4703. *
  4704. * @type {Boolean}
  4705. * @default false
  4706. */
  4707. this.readOnly = readOnly;
  4708. }
  4709. getHash( builder ) {
  4710. return this.name || super.getHash( builder );
  4711. }
  4712. getMemberType( builder, name ) {
  4713. return this.node.getMemberType( builder, name );
  4714. }
  4715. getElementType( builder ) {
  4716. return this.node.getElementType( builder );
  4717. }
  4718. getNodeType( builder ) {
  4719. return this.node.getNodeType( builder );
  4720. }
  4721. generate( builder ) {
  4722. const { node, name, readOnly } = this;
  4723. const { renderer } = builder;
  4724. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4725. let isDeterministic = false;
  4726. let shouldTreatAsReadOnly = false;
  4727. if ( readOnly ) {
  4728. isDeterministic = builder.isDeterministic( node );
  4729. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4730. }
  4731. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4732. const snippet = node.build( builder, vectorType );
  4733. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4734. const propertyName = builder.getPropertyName( nodeVar );
  4735. let declarationPrefix = propertyName;
  4736. if ( shouldTreatAsReadOnly ) {
  4737. if ( isWebGPUBackend ) {
  4738. declarationPrefix = isDeterministic
  4739. ? `const ${ propertyName }`
  4740. : `let ${ propertyName }`;
  4741. } else {
  4742. const count = builder.getArrayCount( node );
  4743. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  4744. }
  4745. }
  4746. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4747. return propertyName;
  4748. }
  4749. }
  4750. /**
  4751. * TSL function for creating a var node.
  4752. *
  4753. * @function
  4754. * @param {Node} node - The node for which a variable should be created.
  4755. * @param {String?} name - The name of the variable in the shader.
  4756. * @returns {VarNode}
  4757. */
  4758. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4759. /**
  4760. * TSL function for creating a var node.
  4761. *
  4762. * @function
  4763. * @param {Node} node - The node for which a variable should be created.
  4764. * @param {String?} name - The name of the variable in the shader.
  4765. * @returns {VarNode}
  4766. */
  4767. const Var = ( node, name = null ) => createVar( node, name ).append();
  4768. /**
  4769. * TSL function for creating a const node.
  4770. *
  4771. * @function
  4772. * @param {Node} node - The node for which a constant should be created.
  4773. * @param {String?} name - The name of the constant in the shader.
  4774. * @returns {VarNode}
  4775. */
  4776. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4777. // Method chaining
  4778. addMethodChaining( 'toVar', Var );
  4779. addMethodChaining( 'toConst', Const );
  4780. // Deprecated
  4781. /**
  4782. * @function
  4783. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4784. *
  4785. * @param {Any} node
  4786. * @returns {VarNode}
  4787. */
  4788. const temp = ( node ) => { // @deprecated, r170
  4789. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4790. return createVar( node );
  4791. };
  4792. addMethodChaining( 'temp', temp );
  4793. /** @module VaryingNode **/
  4794. /**
  4795. * Class for representing shader varyings as nodes. Varyings are create from
  4796. * existing nodes like the following:
  4797. *
  4798. * ```js
  4799. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  4800. * ```
  4801. *
  4802. * @augments Node
  4803. */
  4804. class VaryingNode extends Node {
  4805. static get type() {
  4806. return 'VaryingNode';
  4807. }
  4808. /**
  4809. * Constructs a new varying node.
  4810. *
  4811. * @param {Node} node - The node for which a varying should be created.
  4812. * @param {String?} name - The name of the varying in the shader.
  4813. */
  4814. constructor( node, name = null ) {
  4815. super();
  4816. /**
  4817. * The node for which a varying should be created.
  4818. *
  4819. * @type {Node}
  4820. */
  4821. this.node = node;
  4822. /**
  4823. * The name of the varying in the shader. If no name is defined,
  4824. * the node system auto-generates one.
  4825. *
  4826. * @type {String?}
  4827. * @default null
  4828. */
  4829. this.name = name;
  4830. /**
  4831. * This flag can be used for type testing.
  4832. *
  4833. * @type {Boolean}
  4834. * @readonly
  4835. * @default true
  4836. */
  4837. this.isVaryingNode = true;
  4838. }
  4839. /**
  4840. * The method is overwritten so it always returns `true`.
  4841. *
  4842. * @param {NodeBuilder} builder - The current node builder.
  4843. * @return {Boolean} Whether this node is global or not.
  4844. */
  4845. isGlobal( /*builder*/ ) {
  4846. return true;
  4847. }
  4848. getHash( builder ) {
  4849. return this.name || super.getHash( builder );
  4850. }
  4851. getNodeType( builder ) {
  4852. // VaryingNode is auto type
  4853. return this.node.getNodeType( builder );
  4854. }
  4855. /**
  4856. * This method performs the setup of a varying node with the current node builder.
  4857. *
  4858. * @param {NodeBuilder} builder - The current node builder.
  4859. * @return {NodeVarying} The node varying from the node builder.
  4860. */
  4861. setupVarying( builder ) {
  4862. const properties = builder.getNodeProperties( this );
  4863. let varying = properties.varying;
  4864. if ( varying === undefined ) {
  4865. const name = this.name;
  4866. const type = this.getNodeType( builder );
  4867. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4868. properties.node = this.node;
  4869. }
  4870. // this property can be used to check if the varying can be optimized for a variable
  4871. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4872. return varying;
  4873. }
  4874. setup( builder ) {
  4875. this.setupVarying( builder );
  4876. }
  4877. analyze( builder ) {
  4878. this.setupVarying( builder );
  4879. return this.node.analyze( builder );
  4880. }
  4881. generate( builder ) {
  4882. const properties = builder.getNodeProperties( this );
  4883. const varying = this.setupVarying( builder );
  4884. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  4885. if ( properties.propertyName === undefined || needsReassign ) {
  4886. const type = this.getNodeType( builder );
  4887. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  4888. // force node run in vertex stage
  4889. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  4890. properties.propertyName = propertyName;
  4891. if ( needsReassign ) {
  4892. // once reassign varying in fragment stage
  4893. properties.reassignPosition = false;
  4894. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  4895. properties.reassignPosition = true;
  4896. }
  4897. }
  4898. return builder.getPropertyName( varying );
  4899. }
  4900. }
  4901. /**
  4902. * TSL function for creating a varying node.
  4903. *
  4904. * @function
  4905. * @param {Node} node - The node for which a varying should be created.
  4906. * @param {String?} name - The name of the varying in the shader.
  4907. * @returns {VaryingNode}
  4908. */
  4909. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  4910. /**
  4911. * Computes a node in the vertex stage.
  4912. *
  4913. * @function
  4914. * @param {Node} node - The node which should be executed in the vertex stage.
  4915. * @returns {VaryingNode}
  4916. */
  4917. const vertexStage = ( node ) => varying( node );
  4918. addMethodChaining( 'toVarying', varying );
  4919. addMethodChaining( 'toVertexStage', vertexStage );
  4920. // Deprecated
  4921. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  4922. console.warn( 'TSL.VaryingNode: .varying() has been renamed to .toVarying().' );
  4923. return varying( ...params );
  4924. } );
  4925. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  4926. console.warn( 'TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage().' );
  4927. return varying( ...params );
  4928. } );
  4929. /** @module ColorSpaceFunctions **/
  4930. /**
  4931. * Converts the given color value from sRGB to linear-sRGB color space.
  4932. *
  4933. * @method
  4934. * @param {Node<vec3>} color - The sRGB color.
  4935. * @return {Node<vec3>} The linear-sRGB color.
  4936. */
  4937. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4938. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4939. const b = color.mul( 0.0773993808 );
  4940. const factor = color.lessThanEqual( 0.04045 );
  4941. const rgbResult = mix( a, b, factor );
  4942. return rgbResult;
  4943. } ).setLayout( {
  4944. name: 'sRGBTransferEOTF',
  4945. type: 'vec3',
  4946. inputs: [
  4947. { name: 'color', type: 'vec3' }
  4948. ]
  4949. } );
  4950. /**
  4951. * Converts the given color value from linear-sRGB to sRGB color space.
  4952. *
  4953. * @method
  4954. * @param {Node<vec3>} color - The linear-sRGB color.
  4955. * @return {Node<vec3>} The sRGB color.
  4956. */
  4957. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4958. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4959. const b = color.mul( 12.92 );
  4960. const factor = color.lessThanEqual( 0.0031308 );
  4961. const rgbResult = mix( a, b, factor );
  4962. return rgbResult;
  4963. } ).setLayout( {
  4964. name: 'sRGBTransferOETF',
  4965. type: 'vec3',
  4966. inputs: [
  4967. { name: 'color', type: 'vec3' }
  4968. ]
  4969. } );
  4970. /** @module ColorSpaceNode **/
  4971. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4972. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4973. /**
  4974. * This node represents a color space conversion. Meaning it converts
  4975. * a color value from a source to a target color space.
  4976. *
  4977. * @augments TempNode
  4978. */
  4979. class ColorSpaceNode extends TempNode {
  4980. static get type() {
  4981. return 'ColorSpaceNode';
  4982. }
  4983. /**
  4984. * Constructs a new color space node.
  4985. *
  4986. * @param {Node} colorNode - Represents the color to convert.
  4987. * @param {String} source - The source color space.
  4988. * @param {String} target - The target color space.
  4989. */
  4990. constructor( colorNode, source, target ) {
  4991. super( 'vec4' );
  4992. /**
  4993. * Represents the color to convert.
  4994. *
  4995. * @type {Node}
  4996. */
  4997. this.colorNode = colorNode;
  4998. /**
  4999. * The source color space.
  5000. *
  5001. * @type {String}
  5002. */
  5003. this.source = source;
  5004. /**
  5005. * The target color space.
  5006. *
  5007. * @type {String}
  5008. */
  5009. this.target = target;
  5010. }
  5011. /**
  5012. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5013. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5014. * color management and renderer.
  5015. *
  5016. * @param {NodeBuilder} builder - The current node builder.
  5017. * @param {String} colorSpace - The color space to resolve.
  5018. * @return {String} The resolved color space.
  5019. */
  5020. resolveColorSpace( builder, colorSpace ) {
  5021. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5022. return ColorManagement.workingColorSpace;
  5023. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5024. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5025. }
  5026. return colorSpace;
  5027. }
  5028. setup( builder ) {
  5029. const { colorNode } = this;
  5030. const source = this.resolveColorSpace( builder, this.source );
  5031. const target = this.resolveColorSpace( builder, this.target );
  5032. let outputNode = colorNode;
  5033. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5034. return outputNode;
  5035. }
  5036. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5037. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5038. }
  5039. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5040. outputNode = vec4(
  5041. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5042. outputNode.a
  5043. );
  5044. }
  5045. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5046. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5047. }
  5048. return outputNode;
  5049. }
  5050. }
  5051. /**
  5052. * TSL function for converting a given color node to the current output color space.
  5053. *
  5054. * @function
  5055. * @param {Node} node - Represents the node to convert.
  5056. * @returns {ColorSpaceNode}
  5057. */
  5058. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  5059. /**
  5060. * TSL function for converting a given color node to the current working color space.
  5061. *
  5062. * @function
  5063. * @param {Node} node - Represents the node to convert.
  5064. * @returns {ColorSpaceNode}
  5065. */
  5066. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  5067. /**
  5068. * TSL function for converting a given color node from the current working color space to the given color space.
  5069. *
  5070. * @function
  5071. * @param {Node} node - Represents the node to convert.
  5072. * @param {String} colorSpace - The target color space.
  5073. * @returns {ColorSpaceNode}
  5074. */
  5075. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  5076. /**
  5077. * TSL function for converting a given color node from the given color space to the current working color space.
  5078. *
  5079. * @function
  5080. * @param {Node} node - Represents the node to convert.
  5081. * @param {String} colorSpace - The source color space.
  5082. * @returns {ColorSpaceNode}
  5083. */
  5084. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  5085. /**
  5086. * TSL function for converting a given color node from one color space to another one.
  5087. *
  5088. * @function
  5089. * @param {Node} node - Represents the node to convert.
  5090. * @param {String} sourceColorSpace - The source color space.
  5091. * @param {String} targetColorSpace - The target color space.
  5092. * @returns {ColorSpaceNode}
  5093. */
  5094. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5095. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  5096. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  5097. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5098. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5099. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5100. /** @module ReferenceBaseNode **/
  5101. /**
  5102. * This class is only relevant if the referenced property is array-like.
  5103. * In this case, `ReferenceElementNode` allows to refer to a specific
  5104. * element inside the data structure via an index.
  5105. *
  5106. * @augments ArrayElementNode
  5107. */
  5108. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5109. static get type() {
  5110. return 'ReferenceElementNode';
  5111. }
  5112. /**
  5113. * Constructs a new reference element node.
  5114. *
  5115. * @param {ReferenceBaseNode?} referenceNode - The reference node.
  5116. * @param {Node} indexNode - The index node that defines the element access.
  5117. */
  5118. constructor( referenceNode, indexNode ) {
  5119. super( referenceNode, indexNode );
  5120. /**
  5121. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  5122. * property references to the current node.
  5123. *
  5124. * @type {ReferenceBaseNode?}
  5125. * @default null
  5126. */
  5127. this.referenceNode = referenceNode;
  5128. /**
  5129. * This flag can be used for type testing.
  5130. *
  5131. * @type {Boolean}
  5132. * @readonly
  5133. * @default true
  5134. */
  5135. this.isReferenceElementNode = true;
  5136. }
  5137. /**
  5138. * This method is overwritten since the node type is inferred from
  5139. * the uniform type of the reference node.
  5140. *
  5141. * @return {String} The node type.
  5142. */
  5143. getNodeType() {
  5144. return this.referenceNode.uniformType;
  5145. }
  5146. generate( builder ) {
  5147. const snippet = super.generate( builder );
  5148. const arrayType = this.referenceNode.getNodeType();
  5149. const elementType = this.getNodeType();
  5150. return builder.format( snippet, arrayType, elementType );
  5151. }
  5152. };
  5153. /**
  5154. * Base class for nodes which establishes a reference to a property of another object.
  5155. * In this way, the value of the node is automatically linked to the value of
  5156. * referenced object. Reference nodes internally represent the linked value
  5157. * as a uniform.
  5158. *
  5159. * @augments Node
  5160. */
  5161. class ReferenceBaseNode extends Node {
  5162. static get type() {
  5163. return 'ReferenceBaseNode';
  5164. }
  5165. /**
  5166. * Constructs a new reference base node.
  5167. *
  5168. * @param {String} property - The name of the property the node refers to.
  5169. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  5170. * @param {Object?} [object=null] - The object the property belongs to.
  5171. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5172. */
  5173. constructor( property, uniformType, object = null, count = null ) {
  5174. super();
  5175. /**
  5176. * The name of the property the node refers to.
  5177. *
  5178. * @type {String}
  5179. */
  5180. this.property = property;
  5181. /**
  5182. * The uniform type that should be used to represent the property value.
  5183. *
  5184. * @type {String}
  5185. */
  5186. this.uniformType = uniformType;
  5187. /**
  5188. * The object the property belongs to.
  5189. *
  5190. * @type {Object?}
  5191. * @default null
  5192. */
  5193. this.object = object;
  5194. /**
  5195. * When the linked property is an array, this parameter defines its length.
  5196. *
  5197. * @type {Number?}
  5198. * @default null
  5199. */
  5200. this.count = count;
  5201. /**
  5202. * The property name might have dots so nested properties can be referred.
  5203. * The hierarchy of the names is stored inside this array.
  5204. *
  5205. * @type {Array<String>}
  5206. */
  5207. this.properties = property.split( '.' );
  5208. /**
  5209. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  5210. * since the final reference might be updated from calling code.
  5211. *
  5212. * @type {Object?}
  5213. * @default null
  5214. */
  5215. this.reference = object;
  5216. /**
  5217. * The uniform node that holds the value of the reference node.
  5218. *
  5219. * @type {UniformNode}
  5220. * @default null
  5221. */
  5222. this.node = null;
  5223. /**
  5224. * The uniform group of the internal uniform.
  5225. *
  5226. * @type {UniformGroupNode}
  5227. * @default null
  5228. */
  5229. this.group = null;
  5230. /**
  5231. * Overwritten since reference nodes are updated per object.
  5232. *
  5233. * @type {String}
  5234. * @default 'object'
  5235. */
  5236. this.updateType = NodeUpdateType.OBJECT;
  5237. }
  5238. /**
  5239. * Sets the uniform group for this reference node.
  5240. *
  5241. * @param {UniformGroupNode} group - The uniform group to set.
  5242. * @return {ReferenceBaseNode} A reference to this node.
  5243. */
  5244. setGroup( group ) {
  5245. this.group = group;
  5246. return this;
  5247. }
  5248. /**
  5249. * When the referred property is array-like, this method can be used
  5250. * to access elements via an index node.
  5251. *
  5252. * @param {IndexNode} indexNode - indexNode.
  5253. * @return {ReferenceElementNode} A reference to an element.
  5254. */
  5255. element( indexNode ) {
  5256. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5257. }
  5258. /**
  5259. * Sets the node type which automatically defines the internal
  5260. * uniform type.
  5261. *
  5262. * @param {String} uniformType - The type to set.
  5263. */
  5264. setNodeType( uniformType ) {
  5265. const node = uniform( null, uniformType ).getSelf();
  5266. if ( this.group !== null ) {
  5267. node.setGroup( this.group );
  5268. }
  5269. this.node = node;
  5270. }
  5271. /**
  5272. * This method is overwritten since the node type is inferred from
  5273. * the type of the reference node.
  5274. *
  5275. * @param {NodeBuilder} builder - The current node builder.
  5276. * @return {String} The node type.
  5277. */
  5278. getNodeType( builder ) {
  5279. if ( this.node === null ) {
  5280. this.updateReference( builder );
  5281. this.updateValue();
  5282. }
  5283. return this.node.getNodeType( builder );
  5284. }
  5285. /**
  5286. * Returns the property value from the given referred object.
  5287. *
  5288. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5289. * @return {Any} The value.
  5290. */
  5291. getValueFromReference( object = this.reference ) {
  5292. const { properties } = this;
  5293. let value = object[ properties[ 0 ] ];
  5294. for ( let i = 1; i < properties.length; i ++ ) {
  5295. value = value[ properties[ i ] ];
  5296. }
  5297. return value;
  5298. }
  5299. /**
  5300. * Allows to update the reference based on the given state. The state is only
  5301. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  5302. *
  5303. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5304. * @return {Object} The updated reference.
  5305. */
  5306. updateReference( state ) {
  5307. this.reference = this.object !== null ? this.object : state.object;
  5308. return this.reference;
  5309. }
  5310. /**
  5311. * The output of the reference node is the internal uniform node.
  5312. *
  5313. * @return {UniformNode} The output node.
  5314. */
  5315. setup() {
  5316. this.updateValue();
  5317. return this.node;
  5318. }
  5319. /**
  5320. * Overwritten to to update the internal uniform value.
  5321. *
  5322. * @param {NodeFrame} frame - A reference to the current node frame.
  5323. */
  5324. update( /*frame*/ ) {
  5325. this.updateValue();
  5326. }
  5327. /**
  5328. * Retrieves the value from the referred object property and uses it
  5329. * to updated the internal uniform.
  5330. */
  5331. updateValue() {
  5332. if ( this.node === null ) this.setNodeType( this.uniformType );
  5333. const value = this.getValueFromReference();
  5334. if ( Array.isArray( value ) ) {
  5335. this.node.array = value;
  5336. } else {
  5337. this.node.value = value;
  5338. }
  5339. }
  5340. }
  5341. /**
  5342. * TSL function for creating a reference base node.
  5343. *
  5344. * @function
  5345. * @param {String} name - The name of the property the node refers to.
  5346. * @param {String} type - The uniform type that should be used to represent the property value.
  5347. * @param {Object} object - The object the property belongs to.
  5348. * @returns {ReferenceBaseNode}
  5349. */
  5350. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5351. /** @module RendererReferenceNode **/
  5352. /**
  5353. * This node is a special type of reference node which is intended
  5354. * for linking renderer properties with node values.
  5355. * ```js
  5356. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5357. * ```
  5358. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5359. * automatically be updated.
  5360. *
  5361. * @augments ReferenceBaseNode
  5362. */
  5363. class RendererReferenceNode extends ReferenceBaseNode {
  5364. static get type() {
  5365. return 'RendererReferenceNode';
  5366. }
  5367. /**
  5368. * Constructs a new renderer reference node.
  5369. *
  5370. * @param {String} property - The name of the property the node refers to.
  5371. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5372. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5373. * the node refers to the renderer of the current state.
  5374. */
  5375. constructor( property, inputType, renderer = null ) {
  5376. super( property, inputType, renderer );
  5377. /**
  5378. * The renderer the property belongs to. When no renderer is set,
  5379. * the node refers to the renderer of the current state.
  5380. *
  5381. * @type {Renderer?}
  5382. * @default null
  5383. */
  5384. this.renderer = renderer;
  5385. this.setGroup( renderGroup );
  5386. }
  5387. /**
  5388. * Updates the reference based on the given state. The state is only evaluated
  5389. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5390. *
  5391. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5392. * @return {Object} The updated reference.
  5393. */
  5394. updateReference( state ) {
  5395. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5396. return this.reference;
  5397. }
  5398. }
  5399. /**
  5400. * TSL function for creating a renderer reference node.
  5401. *
  5402. * @function
  5403. * @param {String} name - The name of the property the node refers to.
  5404. * @param {String} type - The uniform type that should be used to represent the property value.
  5405. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5406. * the node refers to the renderer of the current state.
  5407. * @returns {RendererReferenceNode}
  5408. */
  5409. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5410. /** @module ToneMappingNode **/
  5411. /**
  5412. * This node represents a tone mapping operation.
  5413. *
  5414. * @augments TempNode
  5415. */
  5416. class ToneMappingNode extends TempNode {
  5417. static get type() {
  5418. return 'ToneMappingNode';
  5419. }
  5420. /**
  5421. * Constructs a new tone mapping node.
  5422. *
  5423. * @param {Number} toneMapping - The tone mapping type.
  5424. * @param {Node} exposureNode - The tone mapping exposure.
  5425. * @param {Node} [colorNode=null] - The color node to process.
  5426. */
  5427. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5428. super( 'vec3' );
  5429. /**
  5430. * The tone mapping type.
  5431. *
  5432. * @type {Number}
  5433. */
  5434. this.toneMapping = toneMapping;
  5435. /**
  5436. * The tone mapping exposure.
  5437. *
  5438. * @type {Node}
  5439. * @default null
  5440. */
  5441. this.exposureNode = exposureNode;
  5442. /**
  5443. * Represents the color to process.
  5444. *
  5445. * @type {Node?}
  5446. * @default null
  5447. */
  5448. this.colorNode = colorNode;
  5449. }
  5450. /**
  5451. * Overwrites the default `customCacheKey()` implementation by including the tone
  5452. * mapping type into the cache key.
  5453. *
  5454. * @return {Number} The hash.
  5455. */
  5456. customCacheKey() {
  5457. return hash$1( this.toneMapping );
  5458. }
  5459. setup( builder ) {
  5460. const colorNode = this.colorNode || builder.context.color;
  5461. const toneMapping = this.toneMapping;
  5462. if ( toneMapping === NoToneMapping ) return colorNode;
  5463. let outputNode = null;
  5464. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5465. if ( toneMappingFn !== null ) {
  5466. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5467. } else {
  5468. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5469. outputNode = colorNode;
  5470. }
  5471. return outputNode;
  5472. }
  5473. }
  5474. /**
  5475. * TSL function for creating a tone mapping node.
  5476. *
  5477. * @function
  5478. * @param {Number} mapping - The tone mapping type.
  5479. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5480. * @param {Node<vec3> | Color} color - The color node to process.
  5481. * @returns {ToneMappingNode<vec3>}
  5482. */
  5483. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5484. /**
  5485. * TSL object that represents the global tone mapping exposure of the renderer.
  5486. *
  5487. * @type {RendererReferenceNode<vec3>}
  5488. */
  5489. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5490. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5491. /** @module BufferAttributeNode **/
  5492. /**
  5493. * In earlier `three.js` versions it was only possible to define attribute data
  5494. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5495. * on the node level.
  5496. * ```js
  5497. * const geometry = new THREE.PlaneGeometry();
  5498. * const positionAttribute = geometry.getAttribute( 'position' );
  5499. *
  5500. * const colors = [];
  5501. * for ( let i = 0; i < position.count; i ++ ) {
  5502. * colors.push( 1, 0, 0 );
  5503. * }
  5504. *
  5505. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5506. * ```
  5507. * This new approach is especially interesting when geometry data are generated via
  5508. * compute shaders. The below line converts a storage buffer into an attribute node.
  5509. * ```js
  5510. * material.positionNode = positionBuffer.toAttribute();
  5511. * ```
  5512. * @augments InputNode
  5513. */
  5514. class BufferAttributeNode extends InputNode {
  5515. static get type() {
  5516. return 'BufferAttributeNode';
  5517. }
  5518. /**
  5519. * Constructs a new buffer attribute node.
  5520. *
  5521. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5522. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5523. * @param {Number} [bufferStride=0] - The buffer stride.
  5524. * @param {Number} [bufferOffset=0] - The buffer offset.
  5525. */
  5526. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5527. super( value, bufferType );
  5528. /**
  5529. * This flag can be used for type testing.
  5530. *
  5531. * @type {Boolean}
  5532. * @readonly
  5533. * @default true
  5534. */
  5535. this.isBufferNode = true;
  5536. /**
  5537. * The buffer type (e.g. `'vec3'`).
  5538. *
  5539. * @type {String}
  5540. * @default null
  5541. */
  5542. this.bufferType = bufferType;
  5543. /**
  5544. * The buffer stride.
  5545. *
  5546. * @type {Number}
  5547. * @default 0
  5548. */
  5549. this.bufferStride = bufferStride;
  5550. /**
  5551. * The buffer offset.
  5552. *
  5553. * @type {Number}
  5554. * @default 0
  5555. */
  5556. this.bufferOffset = bufferOffset;
  5557. /**
  5558. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5559. * if you are planning to update the attribute data per frame.
  5560. *
  5561. * @type {Number}
  5562. * @default StaticDrawUsage
  5563. */
  5564. this.usage = StaticDrawUsage;
  5565. /**
  5566. * Whether the attribute is instanced or not.
  5567. *
  5568. * @type {Boolean}
  5569. * @default false
  5570. */
  5571. this.instanced = false;
  5572. /**
  5573. * A reference to the buffer attribute.
  5574. *
  5575. * @type {BufferAttribute?}
  5576. * @default null
  5577. */
  5578. this.attribute = null;
  5579. /**
  5580. * `BufferAttributeNode` sets this property to `true` by default.
  5581. *
  5582. * @type {Boolean}
  5583. * @default true
  5584. */
  5585. this.global = true;
  5586. if ( value && value.isBufferAttribute === true ) {
  5587. this.attribute = value;
  5588. this.usage = value.usage;
  5589. this.instanced = value.isInstancedBufferAttribute;
  5590. }
  5591. }
  5592. /**
  5593. * This method is overwritten since the attribute data might be shared
  5594. * and thus the hash should be shared as well.
  5595. *
  5596. * @param {NodeBuilder} builder - The current node builder.
  5597. * @return {String} The hash.
  5598. */
  5599. getHash( builder ) {
  5600. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5601. let bufferData = builder.globalCache.getData( this.value );
  5602. if ( bufferData === undefined ) {
  5603. bufferData = {
  5604. node: this
  5605. };
  5606. builder.globalCache.setData( this.value, bufferData );
  5607. }
  5608. return bufferData.node.uuid;
  5609. }
  5610. return this.uuid;
  5611. }
  5612. /**
  5613. * This method is overwritten since the node type is inferred from
  5614. * the buffer attribute.
  5615. *
  5616. * @param {NodeBuilder} builder - The current node builder.
  5617. * @return {String} The node type.
  5618. */
  5619. getNodeType( builder ) {
  5620. if ( this.bufferType === null ) {
  5621. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5622. }
  5623. return this.bufferType;
  5624. }
  5625. /**
  5626. * Depending on which value was passed to the node, `setup()` behaves
  5627. * differently. If no instance of `BufferAttribute` was passed, the method
  5628. * creates an internal attribute and configures it respectively.
  5629. *
  5630. * @param {NodeBuilder} builder - The current node builder.
  5631. */
  5632. setup( builder ) {
  5633. if ( this.attribute !== null ) return;
  5634. const type = this.getNodeType( builder );
  5635. const array = this.value;
  5636. const itemSize = builder.getTypeLength( type );
  5637. const stride = this.bufferStride || itemSize;
  5638. const offset = this.bufferOffset;
  5639. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5640. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5641. buffer.setUsage( this.usage );
  5642. this.attribute = bufferAttribute;
  5643. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5644. }
  5645. /**
  5646. * Generates the code snippet of the buffer attribute node.
  5647. *
  5648. * @param {NodeBuilder} builder - The current node builder.
  5649. * @return {String} The generated code snippet.
  5650. */
  5651. generate( builder ) {
  5652. const nodeType = this.getNodeType( builder );
  5653. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5654. const propertyName = builder.getPropertyName( nodeAttribute );
  5655. let output = null;
  5656. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5657. this.name = propertyName;
  5658. output = propertyName;
  5659. } else {
  5660. const nodeVarying = varying( this );
  5661. output = nodeVarying.build( builder, nodeType );
  5662. }
  5663. return output;
  5664. }
  5665. /**
  5666. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5667. *
  5668. * @param {NodeBuilder} builder - The current node builder.
  5669. * @return {String} The input type.
  5670. */
  5671. getInputType( /*builder*/ ) {
  5672. return 'bufferAttribute';
  5673. }
  5674. /**
  5675. * Sets the `usage` property to the given value.
  5676. *
  5677. * @param {Number} value - The usage to set.
  5678. * @return {BufferAttributeNode} A reference to this node.
  5679. */
  5680. setUsage( value ) {
  5681. this.usage = value;
  5682. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5683. this.attribute.usage = value;
  5684. }
  5685. return this;
  5686. }
  5687. /**
  5688. * Sets the `instanced` property to the given value.
  5689. *
  5690. * @param {Boolean} value - The value to set.
  5691. * @return {BufferAttributeNode} A reference to this node.
  5692. */
  5693. setInstanced( value ) {
  5694. this.instanced = value;
  5695. return this;
  5696. }
  5697. }
  5698. /**
  5699. * TSL function for creating a buffer attribute node.
  5700. *
  5701. * @function
  5702. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5703. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5704. * @param {Number} [stride=0] - The buffer stride.
  5705. * @param {Number} [offset=0] - The buffer offset.
  5706. * @returns {BufferAttributeNode}
  5707. */
  5708. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5709. /**
  5710. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5711. * Use this function if attribute data are updated per frame.
  5712. *
  5713. * @function
  5714. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5715. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5716. * @param {Number} [stride=0] - The buffer stride.
  5717. * @param {Number} [offset=0] - The buffer offset.
  5718. * @returns {BufferAttributeNode}
  5719. */
  5720. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5721. /**
  5722. * TSL function for creating a buffer attribute node but with enabled instancing
  5723. *
  5724. * @function
  5725. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5726. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5727. * @param {Number} [stride=0] - The buffer stride.
  5728. * @param {Number} [offset=0] - The buffer offset.
  5729. * @returns {BufferAttributeNode}
  5730. */
  5731. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5732. /**
  5733. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5734. *
  5735. * @function
  5736. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5737. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5738. * @param {Number} [stride=0] - The buffer stride.
  5739. * @param {Number} [offset=0] - The buffer offset.
  5740. * @returns {BufferAttributeNode}
  5741. */
  5742. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5743. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5744. /** @module ComputeNode **/
  5745. /**
  5746. * TODO
  5747. *
  5748. * @augments Node
  5749. */
  5750. class ComputeNode extends Node {
  5751. static get type() {
  5752. return 'ComputeNode';
  5753. }
  5754. /**
  5755. * Constructs a new compute node.
  5756. *
  5757. * @param {Node} computeNode - TODO
  5758. * @param {Number} count - TODO.
  5759. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5760. */
  5761. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5762. super( 'void' );
  5763. /**
  5764. * This flag can be used for type testing.
  5765. *
  5766. * @type {Boolean}
  5767. * @readonly
  5768. * @default true
  5769. */
  5770. this.isComputeNode = true;
  5771. /**
  5772. * TODO
  5773. *
  5774. * @type {Node}
  5775. */
  5776. this.computeNode = computeNode;
  5777. /**
  5778. * TODO
  5779. *
  5780. * @type {Number}
  5781. */
  5782. this.count = count;
  5783. /**
  5784. * TODO
  5785. *
  5786. * @type {Array<Number>}
  5787. * @default [64]
  5788. */
  5789. this.workgroupSize = workgroupSize;
  5790. /**
  5791. * TODO
  5792. *
  5793. * @type {Number}
  5794. */
  5795. this.dispatchCount = 0;
  5796. /**
  5797. * TODO
  5798. *
  5799. * @type {Number}
  5800. */
  5801. this.version = 1;
  5802. /**
  5803. * The name or label of the uniform.
  5804. *
  5805. * @type {String}
  5806. * @default ''
  5807. */
  5808. this.name = '';
  5809. /**
  5810. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5811. * is executed once per object by default.
  5812. *
  5813. * @type {String}
  5814. * @default 'object'
  5815. */
  5816. this.updateBeforeType = NodeUpdateType.OBJECT;
  5817. /**
  5818. * TODO
  5819. *
  5820. * @type {Function}
  5821. */
  5822. this.onInitFunction = null;
  5823. this.updateDispatchCount();
  5824. }
  5825. /**
  5826. * Executes the `dispose` event for this node.
  5827. */
  5828. dispose() {
  5829. this.dispatchEvent( { type: 'dispose' } );
  5830. }
  5831. /**
  5832. * Sets the {@link ComputeNode#name} property.
  5833. *
  5834. * @param {String} name - The name of the uniform.
  5835. * @return {ComputeNode} A reference to this node.
  5836. */
  5837. label( name ) {
  5838. this.name = name;
  5839. return this;
  5840. }
  5841. /**
  5842. * TODO
  5843. */
  5844. updateDispatchCount() {
  5845. const { count, workgroupSize } = this;
  5846. let size = workgroupSize[ 0 ];
  5847. for ( let i = 1; i < workgroupSize.length; i ++ )
  5848. size *= workgroupSize[ i ];
  5849. this.dispatchCount = Math.ceil( count / size );
  5850. }
  5851. /**
  5852. * TODO
  5853. *
  5854. * @param {Function} callback - TODO.
  5855. * @return {ComputeNode} A reference to this node.
  5856. */
  5857. onInit( callback ) {
  5858. this.onInitFunction = callback;
  5859. return this;
  5860. }
  5861. /**
  5862. * The method execute the compute for this node.
  5863. *
  5864. * @param {NodeFrame} frame - A reference to the current node frame.
  5865. */
  5866. updateBefore( { renderer } ) {
  5867. renderer.compute( this );
  5868. }
  5869. generate( builder ) {
  5870. const { shaderStage } = builder;
  5871. if ( shaderStage === 'compute' ) {
  5872. const snippet = this.computeNode.build( builder, 'void' );
  5873. if ( snippet !== '' ) {
  5874. builder.addLineFlowCode( snippet, this );
  5875. }
  5876. }
  5877. }
  5878. }
  5879. /**
  5880. * TSL function for creating a compute node.
  5881. *
  5882. * @function
  5883. * @param {Node} node - TODO
  5884. * @param {Number} count - TODO.
  5885. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5886. * @returns {AtomicFunctionNode}
  5887. */
  5888. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5889. addMethodChaining( 'compute', compute );
  5890. /** @module CacheNode **/
  5891. /**
  5892. * This node can be used as a cache management component for another node.
  5893. * Caching is in general used by default in {@link NodeBuilder} but this node
  5894. * allows the usage of a shared parent cache during the build process.
  5895. *
  5896. * @augments Node
  5897. */
  5898. class CacheNode extends Node {
  5899. static get type() {
  5900. return 'CacheNode';
  5901. }
  5902. /**
  5903. * Constructs a new cache node.
  5904. *
  5905. * @param {Node} node - The node that should be cached.
  5906. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5907. */
  5908. constructor( node, parent = true ) {
  5909. super();
  5910. /**
  5911. * The node that should be cached.
  5912. *
  5913. * @type {Node}
  5914. */
  5915. this.node = node;
  5916. /**
  5917. * Whether this node refers to a shared parent cache or not.
  5918. *
  5919. * @type {Boolean}
  5920. * @default true
  5921. */
  5922. this.parent = parent;
  5923. /**
  5924. * This flag can be used for type testing.
  5925. *
  5926. * @type {Boolean}
  5927. * @readonly
  5928. * @default true
  5929. */
  5930. this.isCacheNode = true;
  5931. }
  5932. getNodeType( builder ) {
  5933. const previousCache = builder.getCache();
  5934. const cache = builder.getCacheFromNode( this, this.parent );
  5935. builder.setCache( cache );
  5936. const nodeType = this.node.getNodeType( builder );
  5937. builder.setCache( previousCache );
  5938. return nodeType;
  5939. }
  5940. build( builder, ...params ) {
  5941. const previousCache = builder.getCache();
  5942. const cache = builder.getCacheFromNode( this, this.parent );
  5943. builder.setCache( cache );
  5944. const data = this.node.build( builder, ...params );
  5945. builder.setCache( previousCache );
  5946. return data;
  5947. }
  5948. }
  5949. /**
  5950. * TSL function for creating a cache node.
  5951. *
  5952. * @function
  5953. * @param {Node} node - The node that should be cached.
  5954. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5955. * @returns {CacheNode}
  5956. */
  5957. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5958. addMethodChaining( 'cache', cache );
  5959. /** @module BypassNode **/
  5960. /**
  5961. * The class generates the code of a given node but returns another node in the output.
  5962. * This can be used to call a method or node that does not return a value, i.e.
  5963. * type `void` on an input where returning a value is required. Example:
  5964. *
  5965. * ```js
  5966. * material.colorNode = myColor.bypass( runVoidFn() )
  5967. *```
  5968. *
  5969. * @augments Node
  5970. */
  5971. class BypassNode extends Node {
  5972. static get type() {
  5973. return 'BypassNode';
  5974. }
  5975. /**
  5976. * Constructs a new bypass node.
  5977. *
  5978. * @param {Node} outputNode - The output node.
  5979. * @param {Node} callNode - The call node.
  5980. */
  5981. constructor( outputNode, callNode ) {
  5982. super();
  5983. /**
  5984. * This flag can be used for type testing.
  5985. *
  5986. * @type {Boolean}
  5987. * @readonly
  5988. * @default true
  5989. */
  5990. this.isBypassNode = true;
  5991. /**
  5992. * The output node.
  5993. *
  5994. * @type {Node}
  5995. */
  5996. this.outputNode = outputNode;
  5997. /**
  5998. * The call node.
  5999. *
  6000. * @type {Node}
  6001. */
  6002. this.callNode = callNode;
  6003. }
  6004. getNodeType( builder ) {
  6005. return this.outputNode.getNodeType( builder );
  6006. }
  6007. generate( builder ) {
  6008. const snippet = this.callNode.build( builder, 'void' );
  6009. if ( snippet !== '' ) {
  6010. builder.addLineFlowCode( snippet, this );
  6011. }
  6012. return this.outputNode.build( builder );
  6013. }
  6014. }
  6015. /**
  6016. * TSL function for creating a bypass node.
  6017. *
  6018. * @function
  6019. * @param {Node} outputNode - The output node.
  6020. * @param {Node} callNode - The call node.
  6021. * @returns {BypassNode}
  6022. */
  6023. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  6024. addMethodChaining( 'bypass', bypass );
  6025. /** @module RemapNode **/
  6026. /**
  6027. * This node allows to remap a node value from one range into another. E.g a value of
  6028. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6029. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6030. *
  6031. * @augments Node
  6032. */
  6033. class RemapNode extends Node {
  6034. static get type() {
  6035. return 'RemapNode';
  6036. }
  6037. /**
  6038. * Constructs a new remap node.
  6039. *
  6040. * @param {Node} node - The node that should be remapped.
  6041. * @param {Node} inLowNode - The source or current lower bound of the range.
  6042. * @param {Node} inHighNode - The source or current upper bound of the range.
  6043. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6044. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6045. */
  6046. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6047. super();
  6048. /**
  6049. * The node that should be remapped.
  6050. *
  6051. * @type {Node}
  6052. */
  6053. this.node = node;
  6054. /**
  6055. * The source or current lower bound of the range.
  6056. *
  6057. * @type {Node}
  6058. */
  6059. this.inLowNode = inLowNode;
  6060. /**
  6061. * The source or current upper bound of the range.
  6062. *
  6063. * @type {Node}
  6064. */
  6065. this.inHighNode = inHighNode;
  6066. /**
  6067. * The target lower bound of the range.
  6068. *
  6069. * @type {Node}
  6070. * @default float(0)
  6071. */
  6072. this.outLowNode = outLowNode;
  6073. /**
  6074. * The target upper bound of the range.
  6075. *
  6076. * @type {Node}
  6077. * @default float(1)
  6078. */
  6079. this.outHighNode = outHighNode;
  6080. /**
  6081. * Whether the node value should be clamped before
  6082. * remapping it to the target range.
  6083. *
  6084. * @type {Boolean}
  6085. * @default true
  6086. */
  6087. this.doClamp = true;
  6088. }
  6089. setup() {
  6090. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6091. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6092. if ( doClamp === true ) t = t.clamp();
  6093. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6094. }
  6095. }
  6096. /**
  6097. * TSL function for creating a remap node.
  6098. *
  6099. * @function
  6100. * @param {Node} node - The node that should be remapped.
  6101. * @param {Node} inLowNode - The source or current lower bound of the range.
  6102. * @param {Node} inHighNode - The source or current upper bound of the range.
  6103. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6104. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6105. * @returns {RemapNode}
  6106. */
  6107. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  6108. /**
  6109. * TSL function for creating a remap node, but with enabled clamping.
  6110. *
  6111. * @function
  6112. * @param {Node} node - The node that should be remapped.
  6113. * @param {Node} inLowNode - The source or current lower bound of the range.
  6114. * @param {Node} inHighNode - The source or current upper bound of the range.
  6115. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6116. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6117. * @returns {RemapNode}
  6118. */
  6119. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  6120. addMethodChaining( 'remap', remap );
  6121. addMethodChaining( 'remapClamp', remapClamp );
  6122. /** @module ExpressionNode **/
  6123. /**
  6124. * This class can be used to implement basic expressions in shader code.
  6125. * Basic examples for that are `return`, `continue` or `discard` statements.
  6126. *
  6127. * @augments Node
  6128. */
  6129. class ExpressionNode extends Node {
  6130. static get type() {
  6131. return 'ExpressionNode';
  6132. }
  6133. /**
  6134. * Constructs a new expression node.
  6135. *
  6136. * @param {String} [snippet=''] - The native code snippet.
  6137. * @param {String} [nodeType='void'] - The node type.
  6138. */
  6139. constructor( snippet = '', nodeType = 'void' ) {
  6140. super( nodeType );
  6141. /**
  6142. * The native code snippet.
  6143. *
  6144. * @type {String}
  6145. * @default ''
  6146. */
  6147. this.snippet = snippet;
  6148. }
  6149. generate( builder, output ) {
  6150. const type = this.getNodeType( builder );
  6151. const snippet = this.snippet;
  6152. if ( type === 'void' ) {
  6153. builder.addLineFlowCode( snippet, this );
  6154. } else {
  6155. return builder.format( `( ${ snippet } )`, type, output );
  6156. }
  6157. }
  6158. }
  6159. /**
  6160. * TSL function for creating an expression node.
  6161. *
  6162. * @function
  6163. * @param {String} [snippet=''] - The native code snippet.
  6164. * @param {String} [nodeType='void'] - The node type.
  6165. * @returns {ExpressionNode}
  6166. */
  6167. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  6168. /** @module Discard **/
  6169. /**
  6170. * Represents a `discard` shader operation in TSL.
  6171. *
  6172. * @method
  6173. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6174. * @return {Node} The `discard` expression.
  6175. */
  6176. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  6177. /**
  6178. * Represents a `return` shader operation in TSL.
  6179. *
  6180. * @method
  6181. * @return {ExpressionNode} The `return` expression.
  6182. */
  6183. const Return = () => expression( 'return' ).append();
  6184. addMethodChaining( 'discard', Discard );
  6185. /** @module RenderOutputNode **/
  6186. /**
  6187. * Normally, tone mapping and color conversion happens automatically
  6188. * before outputting pixel too the default (screen) framebuffer. In certain
  6189. * post processing setups this happens to late because certain effects
  6190. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6191. * to apply tone mapping and color space conversion at an arbitrary point
  6192. * in the effect chain.
  6193. *
  6194. * When applying tone mapping and color space conversion manually with this node,
  6195. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6196. *
  6197. * ```js
  6198. * const postProcessing = new PostProcessing( renderer );
  6199. * postProcessing.outputColorTransform = false;
  6200. *
  6201. * const scenePass = pass( scene, camera );
  6202. * const outputPass = renderOutput( scenePass );
  6203. *
  6204. * postProcessing.outputNode = outputPass;
  6205. * ```
  6206. *
  6207. * @augments TempNode
  6208. */
  6209. class RenderOutputNode extends TempNode {
  6210. static get type() {
  6211. return 'RenderOutputNode';
  6212. }
  6213. /**
  6214. * Constructs a new render output node.
  6215. *
  6216. * @param {Node} colorNode - The color node to process.
  6217. * @param {Number} toneMapping - The tone mapping type.
  6218. * @param {String} outputColorSpace - The output color space.
  6219. */
  6220. constructor( colorNode, toneMapping, outputColorSpace ) {
  6221. super( 'vec4' );
  6222. /**
  6223. * The color node to process.
  6224. *
  6225. * @type {Node}
  6226. */
  6227. this.colorNode = colorNode;
  6228. /**
  6229. * The tone mapping type.
  6230. *
  6231. * @type {Number?}
  6232. */
  6233. this.toneMapping = toneMapping;
  6234. /**
  6235. * The output color space.
  6236. *
  6237. * @type {String?}
  6238. */
  6239. this.outputColorSpace = outputColorSpace;
  6240. /**
  6241. * This flag can be used for type testing.
  6242. *
  6243. * @type {Boolean}
  6244. * @readonly
  6245. * @default true
  6246. */
  6247. this.isRenderOutputNode = true;
  6248. }
  6249. setup( { context } ) {
  6250. let outputNode = this.colorNode || context.color;
  6251. // tone mapping
  6252. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6253. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6254. if ( toneMapping !== NoToneMapping ) {
  6255. outputNode = outputNode.toneMapping( toneMapping );
  6256. }
  6257. // working to output color space
  6258. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6259. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6260. }
  6261. return outputNode;
  6262. }
  6263. }
  6264. /**
  6265. * TSL function for creating a posterize node.
  6266. *
  6267. * @function
  6268. * @param {Node} color - The color node to process.
  6269. * @param {Number?} [toneMapping=null] - The tone mapping type.
  6270. * @param {String?} [outputColorSpace=null] - The output color space.
  6271. * @returns {RenderOutputNode}
  6272. */
  6273. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6274. addMethodChaining( 'renderOutput', renderOutput );
  6275. // Non-PURE exports list, side-effects are required here.
  6276. // TSL Base Syntax
  6277. function addNodeElement( name/*, nodeElement*/ ) {
  6278. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6279. }
  6280. /** @module AttributeNode **/
  6281. /**
  6282. * Base class for representing shader attributes as nodes.
  6283. *
  6284. * @augments Node
  6285. */
  6286. class AttributeNode extends Node {
  6287. static get type() {
  6288. return 'AttributeNode';
  6289. }
  6290. /**
  6291. * Constructs a new attribute node.
  6292. *
  6293. * @param {String} attributeName - The name of the attribute.
  6294. * @param {String?} nodeType - The node type.
  6295. */
  6296. constructor( attributeName, nodeType = null ) {
  6297. super( nodeType );
  6298. /**
  6299. * `AttributeNode` sets this property to `true` by default.
  6300. *
  6301. * @type {Boolean}
  6302. * @default true
  6303. */
  6304. this.global = true;
  6305. this._attributeName = attributeName;
  6306. }
  6307. getHash( builder ) {
  6308. return this.getAttributeName( builder );
  6309. }
  6310. getNodeType( builder ) {
  6311. let nodeType = this.nodeType;
  6312. if ( nodeType === null ) {
  6313. const attributeName = this.getAttributeName( builder );
  6314. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6315. const attribute = builder.geometry.getAttribute( attributeName );
  6316. nodeType = builder.getTypeFromAttribute( attribute );
  6317. } else {
  6318. nodeType = 'float';
  6319. }
  6320. }
  6321. return nodeType;
  6322. }
  6323. /**
  6324. * Sets the attribute name to the given value. The method can be
  6325. * overwritten in derived classes if the final name must be computed
  6326. * analytically.
  6327. *
  6328. * @param {String} attributeName - The name of the attribute.
  6329. * @return {AttributeNode} A reference to this node.
  6330. */
  6331. setAttributeName( attributeName ) {
  6332. this._attributeName = attributeName;
  6333. return this;
  6334. }
  6335. /**
  6336. * Returns the attribute name of this node. The method can be
  6337. * overwritten in derived classes if the final name must be computed
  6338. * analytically.
  6339. *
  6340. * @param {NodeBuilder} builder - The current node builder.
  6341. * @return {String} The attribute name.
  6342. */
  6343. getAttributeName( /*builder*/ ) {
  6344. return this._attributeName;
  6345. }
  6346. generate( builder ) {
  6347. const attributeName = this.getAttributeName( builder );
  6348. const nodeType = this.getNodeType( builder );
  6349. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6350. if ( geometryAttribute === true ) {
  6351. const attribute = builder.geometry.getAttribute( attributeName );
  6352. const attributeType = builder.getTypeFromAttribute( attribute );
  6353. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6354. if ( builder.shaderStage === 'vertex' ) {
  6355. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6356. } else {
  6357. const nodeVarying = varying( this );
  6358. return nodeVarying.build( builder, nodeType );
  6359. }
  6360. } else {
  6361. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6362. return builder.generateConst( nodeType );
  6363. }
  6364. }
  6365. serialize( data ) {
  6366. super.serialize( data );
  6367. data.global = this.global;
  6368. data._attributeName = this._attributeName;
  6369. }
  6370. deserialize( data ) {
  6371. super.deserialize( data );
  6372. this.global = data.global;
  6373. this._attributeName = data._attributeName;
  6374. }
  6375. }
  6376. /**
  6377. * TSL function for creating an attribute node.
  6378. *
  6379. * @function
  6380. * @param {String} name - The name of the attribute.
  6381. * @param {String?} nodeType - The node type.
  6382. * @returns {AttributeNode}
  6383. */
  6384. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6385. /** @module UV **/
  6386. /**
  6387. * TSL function for creating an uv attribute node with the given index.
  6388. *
  6389. * @function
  6390. * @param {Number} [index=0] - The uv index.
  6391. * @return {AttributeNode<vec2>} The uv attribute node.
  6392. */
  6393. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6394. /** @module TextureSizeNode **/
  6395. /**
  6396. * A node that represents the dimensions of a texture. The texture size is
  6397. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6398. * or `textureSize()`.
  6399. *
  6400. * @augments Node
  6401. */
  6402. class TextureSizeNode extends Node {
  6403. static get type() {
  6404. return 'TextureSizeNode';
  6405. }
  6406. /**
  6407. * Constructs a new texture size node.
  6408. *
  6409. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6410. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6411. */
  6412. constructor( textureNode, levelNode = null ) {
  6413. super( 'uvec2' );
  6414. /**
  6415. * This flag can be used for type testing.
  6416. *
  6417. * @type {Boolean}
  6418. * @readonly
  6419. * @default true
  6420. */
  6421. this.isTextureSizeNode = true;
  6422. /**
  6423. * A texture node which size should be retrieved.
  6424. *
  6425. * @type {TextureNode}
  6426. */
  6427. this.textureNode = textureNode;
  6428. /**
  6429. * A level node which defines the requested mip.
  6430. *
  6431. * @type {Node<int>}
  6432. * @default null
  6433. */
  6434. this.levelNode = levelNode;
  6435. }
  6436. generate( builder, output ) {
  6437. const textureProperty = this.textureNode.build( builder, 'property' );
  6438. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6439. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6440. }
  6441. }
  6442. /**
  6443. * TSL function for creating a texture size node.
  6444. *
  6445. * @function
  6446. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6447. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6448. * @returns {TextureSizeNode}
  6449. */
  6450. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6451. /** @module MatcapUVNode **/
  6452. /**
  6453. * A special type of uniform node that computes the
  6454. * maximum mipmap level for a given texture node.
  6455. *
  6456. * ```js
  6457. * const level = maxMipLevel( textureNode );
  6458. * ```
  6459. *
  6460. * @augments module:UniformNode~UniformNode
  6461. */
  6462. class MaxMipLevelNode extends UniformNode {
  6463. static get type() {
  6464. return 'MaxMipLevelNode';
  6465. }
  6466. /**
  6467. * Constructs a new max mip level node.
  6468. *
  6469. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6470. */
  6471. constructor( textureNode ) {
  6472. super( 0 );
  6473. /**
  6474. * The texture node to compute the max mip level for.
  6475. *
  6476. * @private
  6477. * @type {TextureNode}
  6478. */
  6479. this._textureNode = textureNode;
  6480. /**
  6481. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6482. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6483. *
  6484. * @type {String}
  6485. * @default 'frame'
  6486. */
  6487. this.updateType = NodeUpdateType.FRAME;
  6488. }
  6489. /**
  6490. * The texture node to compute the max mip level for.
  6491. *
  6492. * @readonly
  6493. * @type {TextureNode}
  6494. */
  6495. get textureNode() {
  6496. return this._textureNode;
  6497. }
  6498. /**
  6499. * The texture.
  6500. *
  6501. * @readonly
  6502. * @type {Texture}
  6503. */
  6504. get texture() {
  6505. return this._textureNode.value;
  6506. }
  6507. update() {
  6508. const texture = this.texture;
  6509. const images = texture.images;
  6510. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6511. if ( image && image.width !== undefined ) {
  6512. const { width, height } = image;
  6513. this.value = Math.log2( Math.max( width, height ) );
  6514. }
  6515. }
  6516. }
  6517. /**
  6518. * TSL function for creating a max mip level node.
  6519. *
  6520. * @function
  6521. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6522. * @returns {MaxMipLevelNode}
  6523. */
  6524. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6525. /** @module TextureNode **/
  6526. /**
  6527. * This type of uniform node represents a 2D texture.
  6528. *
  6529. * @augments module:UniformNode~UniformNode
  6530. */
  6531. class TextureNode extends UniformNode {
  6532. static get type() {
  6533. return 'TextureNode';
  6534. }
  6535. /**
  6536. * Constructs a new texture node.
  6537. *
  6538. * @param {Texture} value - The texture.
  6539. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6540. * @param {Node<int>?} [levelNode=null] - The level node.
  6541. * @param {Node<float>?} [biasNode=null] - The bias node.
  6542. */
  6543. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6544. super( value );
  6545. /**
  6546. * This flag can be used for type testing.
  6547. *
  6548. * @type {Boolean}
  6549. * @readonly
  6550. * @default true
  6551. */
  6552. this.isTextureNode = true;
  6553. /**
  6554. * Represents the texture coordinates.
  6555. *
  6556. * @type {Node<vec2|vec3>?}
  6557. * @default null
  6558. */
  6559. this.uvNode = uvNode;
  6560. /**
  6561. * Represents the mip level that should be selected.
  6562. *
  6563. * @type {Node<int>?}
  6564. * @default null
  6565. */
  6566. this.levelNode = levelNode;
  6567. /**
  6568. * Represents the bias to be applied during level-of-detail computation.
  6569. *
  6570. * @type {Node<float>?}
  6571. * @default null
  6572. */
  6573. this.biasNode = biasNode;
  6574. /**
  6575. * Represents a reference value a texture sample is compared to.
  6576. *
  6577. * @type {Node<float>?}
  6578. * @default null
  6579. */
  6580. this.compareNode = null;
  6581. /**
  6582. * When using texture arrays, the depth node defines the layer to select.
  6583. *
  6584. * @type {Node<int>?}
  6585. * @default null
  6586. */
  6587. this.depthNode = null;
  6588. /**
  6589. * When defined, a texture is sampled using explicit gradients.
  6590. *
  6591. * @type {Array<Node<vec2>>?}
  6592. * @default null
  6593. */
  6594. this.gradNode = null;
  6595. /**
  6596. * Whether texture values should be sampled or fetched.
  6597. *
  6598. * @type {Boolean}
  6599. * @default true
  6600. */
  6601. this.sampler = true;
  6602. /**
  6603. * Whether the uv transformation matrix should be
  6604. * automatically updated or not. Use `setUpdateMatrix()`
  6605. * if you want to change the value of the property.
  6606. *
  6607. * @type {Boolean}
  6608. * @default false
  6609. */
  6610. this.updateMatrix = false;
  6611. /**
  6612. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6613. * sets the value to `frame` when the uv transformation matrix should
  6614. * automatically be updated.
  6615. *
  6616. * @type {String}
  6617. * @default 'none'
  6618. */
  6619. this.updateType = NodeUpdateType.NONE;
  6620. /**
  6621. * The reference node.
  6622. *
  6623. * @type {Node?}
  6624. * @default null
  6625. */
  6626. this.referenceNode = null;
  6627. /**
  6628. * The texture value is stored in a private property.
  6629. *
  6630. * @private
  6631. * @type {Texture}
  6632. */
  6633. this._value = value;
  6634. /**
  6635. * The uniform node that represents the uv transformation matrix.
  6636. *
  6637. * @private
  6638. * @type {UniformNode<mat3>?}
  6639. */
  6640. this._matrixUniform = null;
  6641. this.setUpdateMatrix( uvNode === null );
  6642. }
  6643. set value( value ) {
  6644. if ( this.referenceNode ) {
  6645. this.referenceNode.value = value;
  6646. } else {
  6647. this._value = value;
  6648. }
  6649. }
  6650. /**
  6651. * The texture value.
  6652. *
  6653. * @type {Texture}
  6654. */
  6655. get value() {
  6656. return this.referenceNode ? this.referenceNode.value : this._value;
  6657. }
  6658. /**
  6659. * Overwritten since the uniform hash is defined by the texture's UUID.
  6660. *
  6661. * @param {NodeBuilder} builder - The current node builder.
  6662. * @return {String} The uniform hash.
  6663. */
  6664. getUniformHash( /*builder*/ ) {
  6665. return this.value.uuid;
  6666. }
  6667. /**
  6668. * Overwritten since the node type is inferred from the texture type.
  6669. *
  6670. * @param {NodeBuilder} builder - The current node builder.
  6671. * @return {String} The node type.
  6672. */
  6673. getNodeType( /*builder*/ ) {
  6674. if ( this.value.isDepthTexture === true ) return 'float';
  6675. if ( this.value.type === UnsignedIntType ) {
  6676. return 'uvec4';
  6677. } else if ( this.value.type === IntType ) {
  6678. return 'ivec4';
  6679. }
  6680. return 'vec4';
  6681. }
  6682. /**
  6683. * Overwrites the default implementation to return a fixed value `'texture'`.
  6684. *
  6685. * @param {NodeBuilder} builder - The current node builder.
  6686. * @return {String} The input type.
  6687. */
  6688. getInputType( /*builder*/ ) {
  6689. return 'texture';
  6690. }
  6691. /**
  6692. * Returns a default uvs based on the current texture's channel.
  6693. *
  6694. * @return {AttributeNode<vec2>} The default uvs.
  6695. */
  6696. getDefaultUV() {
  6697. return uv( this.value.channel );
  6698. }
  6699. /**
  6700. * Overwritten to always return the texture reference of the node.
  6701. *
  6702. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6703. * @return {Texture} The texture reference.
  6704. */
  6705. updateReference( /*state*/ ) {
  6706. return this.value;
  6707. }
  6708. /**
  6709. * Transforms the given uv node with the texture transformation matrix.
  6710. *
  6711. * @param {Node} uvNode - The uv node to transform.
  6712. * @return {Node} The transformed uv node.
  6713. */
  6714. getTransformedUV( uvNode ) {
  6715. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6716. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6717. }
  6718. /**
  6719. * Defines whether the uv transformation matrix should automatically be updated or not.
  6720. *
  6721. * @param {Boolean} value - The update toggle.
  6722. * @return {TextureNode} A reference to this node.
  6723. */
  6724. setUpdateMatrix( value ) {
  6725. this.updateMatrix = value;
  6726. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6727. return this;
  6728. }
  6729. /**
  6730. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6731. * to modify the uv node for correct sampling.
  6732. *
  6733. * @param {NodeBuilder} builder - The current node builder.
  6734. * @param {Node} uvNode - The uv node to setup.
  6735. * @return {Node} The updated uv node.
  6736. */
  6737. setupUV( builder, uvNode ) {
  6738. const texture = this.value;
  6739. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6740. if ( this.sampler ) {
  6741. uvNode = uvNode.flipY();
  6742. } else {
  6743. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6744. }
  6745. }
  6746. return uvNode;
  6747. }
  6748. /**
  6749. * Setups texture node by preparing the internal nodes for code generation.
  6750. *
  6751. * @param {NodeBuilder} builder - The current node builder.
  6752. */
  6753. setup( builder ) {
  6754. const properties = builder.getNodeProperties( this );
  6755. properties.referenceNode = this.referenceNode;
  6756. //
  6757. const texture = this.value;
  6758. if ( ! texture || texture.isTexture !== true ) {
  6759. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6760. }
  6761. //
  6762. let uvNode = this.uvNode;
  6763. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6764. uvNode = builder.context.getUV( this );
  6765. }
  6766. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6767. if ( this.updateMatrix === true ) {
  6768. uvNode = this.getTransformedUV( uvNode );
  6769. }
  6770. uvNode = this.setupUV( builder, uvNode );
  6771. //
  6772. let levelNode = this.levelNode;
  6773. if ( levelNode === null && builder.context.getTextureLevel ) {
  6774. levelNode = builder.context.getTextureLevel( this );
  6775. }
  6776. //
  6777. properties.uvNode = uvNode;
  6778. properties.levelNode = levelNode;
  6779. properties.biasNode = this.biasNode;
  6780. properties.compareNode = this.compareNode;
  6781. properties.gradNode = this.gradNode;
  6782. properties.depthNode = this.depthNode;
  6783. }
  6784. /**
  6785. * Generates the uv code snippet.
  6786. *
  6787. * @param {NodeBuilder} builder - The current node builder.
  6788. * @param {Node} uvNode - The uv node to generate code for.
  6789. * @return {String} The generated code snippet.
  6790. */
  6791. generateUV( builder, uvNode ) {
  6792. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6793. }
  6794. /**
  6795. * Generates the snippet for the texture sampling.
  6796. *
  6797. * @param {NodeBuilder} builder - The current node builder.
  6798. * @param {String} textureProperty - The texture property.
  6799. * @param {String} uvSnippet - The uv snippet.
  6800. * @param {String?} levelSnippet - The level snippet.
  6801. * @param {String?} biasSnippet - The bias snippet.
  6802. * @param {String?} depthSnippet - The depth snippet.
  6803. * @param {String?} compareSnippet - The compare snippet.
  6804. * @param {Array<String>?} gradSnippet - The grad snippet.
  6805. * @return {String} The generated code snippet.
  6806. */
  6807. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6808. const texture = this.value;
  6809. let snippet;
  6810. if ( levelSnippet ) {
  6811. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6812. } else if ( biasSnippet ) {
  6813. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6814. } else if ( gradSnippet ) {
  6815. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6816. } else if ( compareSnippet ) {
  6817. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6818. } else if ( this.sampler === false ) {
  6819. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6820. } else {
  6821. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6822. }
  6823. return snippet;
  6824. }
  6825. /**
  6826. * Generates the code snippet of the texture node.
  6827. *
  6828. * @param {NodeBuilder} builder - The current node builder.
  6829. * @param {String} output - The current output.
  6830. * @return {String} The generated code snippet.
  6831. */
  6832. generate( builder, output ) {
  6833. const texture = this.value;
  6834. const properties = builder.getNodeProperties( this );
  6835. const textureProperty = super.generate( builder, 'property' );
  6836. if ( output === 'sampler' ) {
  6837. return textureProperty + '_sampler';
  6838. } else if ( builder.isReference( output ) ) {
  6839. return textureProperty;
  6840. } else {
  6841. const nodeData = builder.getDataFromNode( this );
  6842. let propertyName = nodeData.propertyName;
  6843. if ( propertyName === undefined ) {
  6844. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6845. const uvSnippet = this.generateUV( builder, uvNode );
  6846. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6847. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6848. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6849. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6850. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6851. const nodeVar = builder.getVarFromNode( this );
  6852. propertyName = builder.getPropertyName( nodeVar );
  6853. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6854. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6855. nodeData.snippet = snippet;
  6856. nodeData.propertyName = propertyName;
  6857. }
  6858. let snippet = propertyName;
  6859. const nodeType = this.getNodeType( builder );
  6860. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6861. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6862. }
  6863. return builder.format( snippet, nodeType, output );
  6864. }
  6865. }
  6866. /**
  6867. * Sets the sampler value.
  6868. *
  6869. * @param {Boolean} value - The sampler value to set.
  6870. * @return {TextureNode} A reference to this texture node.
  6871. */
  6872. setSampler( value ) {
  6873. this.sampler = value;
  6874. return this;
  6875. }
  6876. /**
  6877. * Returns the sampler value.
  6878. *
  6879. * @return {Boolean} The sampler value.
  6880. */
  6881. getSampler() {
  6882. return this.sampler;
  6883. }
  6884. // @TODO: Move to TSL
  6885. /**
  6886. * @function
  6887. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  6888. *
  6889. * @param {Node} uvNode - The uv node.
  6890. * @return {TextureNode} A texture node representing the texture sample.
  6891. */
  6892. uv( uvNode ) { // @deprecated, r172
  6893. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6894. return this.sample( uvNode );
  6895. }
  6896. /**
  6897. * Samples the texture with the given uv node.
  6898. *
  6899. * @param {Node} uvNode - The uv node.
  6900. * @return {TextureNode} A texture node representing the texture sample.
  6901. */
  6902. sample( uvNode ) {
  6903. const textureNode = this.clone();
  6904. textureNode.uvNode = nodeObject( uvNode );
  6905. textureNode.referenceNode = this.getSelf();
  6906. return nodeObject( textureNode );
  6907. }
  6908. /**
  6909. * Samples a blurred version of the texture by defining an internal bias.
  6910. *
  6911. * @param {Node<float>} amountNode - How blurred the texture should be.
  6912. * @return {TextureNode} A texture node representing the texture sample.
  6913. */
  6914. blur( amountNode ) {
  6915. const textureNode = this.clone();
  6916. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6917. textureNode.referenceNode = this.getSelf();
  6918. return nodeObject( textureNode );
  6919. }
  6920. /**
  6921. * Samples a specific mip of the texture.
  6922. *
  6923. * @param {Node<int>} levelNode - The mip level to sample.
  6924. * @return {TextureNode} A texture node representing the texture sample.
  6925. */
  6926. level( levelNode ) {
  6927. const textureNode = this.clone();
  6928. textureNode.levelNode = nodeObject( levelNode );
  6929. textureNode.referenceNode = this.getSelf();
  6930. return nodeObject( textureNode );
  6931. }
  6932. /**
  6933. * Returns the texture size of the requested level.
  6934. *
  6935. * @param {Node<int>} levelNode - The level to compute the size for.
  6936. * @return {TextureSizeNode} The texture size.
  6937. */
  6938. size( levelNode ) {
  6939. return textureSize( this, levelNode );
  6940. }
  6941. /**
  6942. * Samples the texture with the given bias.
  6943. *
  6944. * @param {Node<float>} biasNode - The bias node.
  6945. * @return {TextureNode} A texture node representing the texture sample.
  6946. */
  6947. bias( biasNode ) {
  6948. const textureNode = this.clone();
  6949. textureNode.biasNode = nodeObject( biasNode );
  6950. textureNode.referenceNode = this.getSelf();
  6951. return nodeObject( textureNode );
  6952. }
  6953. /**
  6954. * Samples the texture by executing a compare operation.
  6955. *
  6956. * @param {Node<float>} compareNode - The node that defines the compare value.
  6957. * @return {TextureNode} A texture node representing the texture sample.
  6958. */
  6959. compare( compareNode ) {
  6960. const textureNode = this.clone();
  6961. textureNode.compareNode = nodeObject( compareNode );
  6962. textureNode.referenceNode = this.getSelf();
  6963. return nodeObject( textureNode );
  6964. }
  6965. /**
  6966. * Samples the texture using an explicit gradient.
  6967. *
  6968. * @param {Node<vec2>} gradNodeX - The gradX node.
  6969. * @param {Node<vec2>} gradNodeY - The gradY node.
  6970. * @return {TextureNode} A texture node representing the texture sample.
  6971. */
  6972. grad( gradNodeX, gradNodeY ) {
  6973. const textureNode = this.clone();
  6974. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6975. textureNode.referenceNode = this.getSelf();
  6976. return nodeObject( textureNode );
  6977. }
  6978. /**
  6979. * Samples the texture by defining a depth node.
  6980. *
  6981. * @param {Node<int>} depthNode - The depth node.
  6982. * @return {TextureNode} A texture node representing the texture sample.
  6983. */
  6984. depth( depthNode ) {
  6985. const textureNode = this.clone();
  6986. textureNode.depthNode = nodeObject( depthNode );
  6987. textureNode.referenceNode = this.getSelf();
  6988. return nodeObject( textureNode );
  6989. }
  6990. // --
  6991. serialize( data ) {
  6992. super.serialize( data );
  6993. data.value = this.value.toJSON( data.meta ).uuid;
  6994. data.sampler = this.sampler;
  6995. data.updateMatrix = this.updateMatrix;
  6996. data.updateType = this.updateType;
  6997. }
  6998. deserialize( data ) {
  6999. super.deserialize( data );
  7000. this.value = data.meta.textures[ data.value ];
  7001. this.sampler = data.sampler;
  7002. this.updateMatrix = data.updateMatrix;
  7003. this.updateType = data.updateType;
  7004. }
  7005. /**
  7006. * The update is used to implement the update of the uv transformation matrix.
  7007. */
  7008. update() {
  7009. const texture = this.value;
  7010. const matrixUniform = this._matrixUniform;
  7011. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7012. if ( texture.matrixAutoUpdate === true ) {
  7013. texture.updateMatrix();
  7014. }
  7015. }
  7016. /**
  7017. * Clones the texture node.
  7018. *
  7019. * @return {TextureNode} The cloned texture node.
  7020. */
  7021. clone() {
  7022. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7023. newNode.sampler = this.sampler;
  7024. return newNode;
  7025. }
  7026. }
  7027. /**
  7028. * TSL function for creating a texture node.
  7029. *
  7030. * @function
  7031. * @param {Texture} value - The texture.
  7032. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  7033. * @param {Node<int>?} [levelNode=null] - The level node.
  7034. * @param {Node<float>?} [biasNode=null] - The bias node.
  7035. * @returns {TextureNode}
  7036. */
  7037. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  7038. /**
  7039. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7040. *
  7041. * @function
  7042. * @param {Texture} value - The texture.
  7043. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  7044. * @param {Node<int>?} [levelNode=null] - The level node.
  7045. * @param {Node<float>?} [biasNode=null] - The bias node.
  7046. * @returns {TextureNode}
  7047. */
  7048. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7049. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7050. /**
  7051. * Converts a texture or texture node to a sampler.
  7052. *
  7053. * @function
  7054. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  7055. * @returns {Node}
  7056. */
  7057. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  7058. /** @module BufferNode **/
  7059. /**
  7060. * A special type of uniform node which represents array-like data
  7061. * as uniform buffers. The access usually happens via `element()`
  7062. * which returns an instance of {@link ArrayElementNode}. For example:
  7063. *
  7064. * ```js
  7065. * const bufferNode = buffer( array, 'mat4', count );
  7066. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7067. * ```
  7068. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7069. * since it handles more input types and automatically cares about buffer paddings.
  7070. *
  7071. * @augments module:UniformNode~UniformNode
  7072. */
  7073. class BufferNode extends UniformNode {
  7074. static get type() {
  7075. return 'BufferNode';
  7076. }
  7077. /**
  7078. * Constructs a new buffer node.
  7079. *
  7080. * @param {Array<Number>} value - Array-like buffer data.
  7081. * @param {String} bufferType - The data type of the buffer.
  7082. * @param {Number} [bufferCount=0] - The count of buffer elements.
  7083. */
  7084. constructor( value, bufferType, bufferCount = 0 ) {
  7085. super( value, bufferType );
  7086. /**
  7087. * This flag can be used for type testing.
  7088. *
  7089. * @type {Boolean}
  7090. * @readonly
  7091. * @default true
  7092. */
  7093. this.isBufferNode = true;
  7094. /**
  7095. * The data type of the buffer.
  7096. *
  7097. * @type {String}
  7098. */
  7099. this.bufferType = bufferType;
  7100. /**
  7101. * The uniform node that holds the value of the reference node.
  7102. *
  7103. * @type {Number}
  7104. * @default 0
  7105. */
  7106. this.bufferCount = bufferCount;
  7107. }
  7108. /**
  7109. * The data type of the buffer elements.
  7110. *
  7111. * @param {NodeBuilder} builder - The current node builder.
  7112. * @return {String} The element type.
  7113. */
  7114. getElementType( builder ) {
  7115. return this.getNodeType( builder );
  7116. }
  7117. /**
  7118. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7119. *
  7120. * @param {NodeBuilder} builder - The current node builder.
  7121. * @return {String} The input type.
  7122. */
  7123. getInputType( /*builder*/ ) {
  7124. return 'buffer';
  7125. }
  7126. }
  7127. /**
  7128. * TSL function for creating a buffer node.
  7129. *
  7130. * @function
  7131. * @param {Array} value - Array-like buffer data.
  7132. * @param {String} type - The data type of a buffer element.
  7133. * @param {Number} count - The count of buffer elements.
  7134. * @returns {BufferNode}
  7135. */
  7136. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7137. /** @module UniformArrayNode **/
  7138. /**
  7139. * Represents the element access on uniform array nodes.
  7140. *
  7141. * @augments ArrayElementNode
  7142. */
  7143. class UniformArrayElementNode extends ArrayElementNode {
  7144. static get type() {
  7145. return 'UniformArrayElementNode';
  7146. }
  7147. /**
  7148. * Constructs a new buffer node.
  7149. *
  7150. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7151. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7152. */
  7153. constructor( uniformArrayNode, indexNode ) {
  7154. super( uniformArrayNode, indexNode );
  7155. /**
  7156. * This flag can be used for type testing.
  7157. *
  7158. * @type {Boolean}
  7159. * @readonly
  7160. * @default true
  7161. */
  7162. this.isArrayBufferElementNode = true;
  7163. }
  7164. generate( builder ) {
  7165. const snippet = super.generate( builder );
  7166. const type = this.getNodeType();
  7167. const paddedType = this.node.getPaddedType();
  7168. return builder.format( snippet, paddedType, type );
  7169. }
  7170. }
  7171. /**
  7172. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  7173. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  7174. * data types in the array (e.g `three.js` primitives) and automatically
  7175. * manage buffer padding. It should be the first choice when working with
  7176. * uniforms buffers.
  7177. * ```js
  7178. * const tintColors = uniformArray( [
  7179. * new Color( 1, 0, 0 ),
  7180. * new Color( 0, 1, 0 ),
  7181. * new Color( 0, 0, 1 )
  7182. * ], 'color' );
  7183. *
  7184. * const redColor = tintColors.element( 0 );
  7185. *
  7186. * @augments module:BufferNode~BufferNode
  7187. */
  7188. class UniformArrayNode extends BufferNode {
  7189. static get type() {
  7190. return 'UniformArrayNode';
  7191. }
  7192. /**
  7193. * Constructs a new uniform array node.
  7194. *
  7195. * @param {Array<Any>} value - Array holding the buffer data.
  7196. * @param {String?} [elementType=null] - The data type of a buffer element.
  7197. */
  7198. constructor( value, elementType = null ) {
  7199. super( null );
  7200. /**
  7201. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  7202. * hold number primitives as well as three.js objects like vectors, matrices
  7203. * or colors.
  7204. *
  7205. * @type {Array<Any>}
  7206. */
  7207. this.array = value;
  7208. /**
  7209. * The data type of an array element.
  7210. *
  7211. * @type {String}
  7212. */
  7213. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7214. /**
  7215. * The padded type. Uniform buffers must conform to a certain buffer layout
  7216. * so a separate type is computed to ensure correct buffer size.
  7217. *
  7218. * @type {String}
  7219. */
  7220. this.paddedType = this.getPaddedType();
  7221. /**
  7222. * Overwritten since uniform array nodes are updated per render.
  7223. *
  7224. * @type {String}
  7225. * @default 'render'
  7226. */
  7227. this.updateType = NodeUpdateType.RENDER;
  7228. /**
  7229. * This flag can be used for type testing.
  7230. *
  7231. * @type {Boolean}
  7232. * @readonly
  7233. * @default true
  7234. */
  7235. this.isArrayBufferNode = true;
  7236. }
  7237. /**
  7238. * This method is overwritten since the node type is inferred from the
  7239. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7240. *
  7241. * @param {NodeBuilder} builder - The current node builder.
  7242. * @return {String} The node type.
  7243. */
  7244. getNodeType( /*builder*/ ) {
  7245. return this.paddedType;
  7246. }
  7247. /**
  7248. * The data type of the array elements.
  7249. *
  7250. * @param {NodeBuilder} builder - The current node builder.
  7251. * @return {String} The element type.
  7252. */
  7253. getElementType() {
  7254. return this.elementType;
  7255. }
  7256. /**
  7257. * Returns the padded type based on the element type.
  7258. *
  7259. * @return {String} The padded type.
  7260. */
  7261. getPaddedType() {
  7262. const elementType = this.elementType;
  7263. let paddedType = 'vec4';
  7264. if ( elementType === 'mat2' ) {
  7265. paddedType = 'mat2';
  7266. } else if ( /mat/.test( elementType ) === true ) {
  7267. paddedType = 'mat4';
  7268. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7269. paddedType = 'ivec4';
  7270. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7271. paddedType = 'uvec4';
  7272. }
  7273. return paddedType;
  7274. }
  7275. /**
  7276. * The update makes sure to correctly transfer the data from the (complex) objects
  7277. * in the array to the internal, correctly padded value buffer.
  7278. *
  7279. * @param {NodeFrame} frame - A reference to the current node frame.
  7280. */
  7281. update( /*frame*/ ) {
  7282. const { array, value } = this;
  7283. const elementType = this.elementType;
  7284. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7285. for ( let i = 0; i < array.length; i ++ ) {
  7286. const index = i * 4;
  7287. value[ index ] = array[ i ];
  7288. }
  7289. } else if ( elementType === 'color' ) {
  7290. for ( let i = 0; i < array.length; i ++ ) {
  7291. const index = i * 4;
  7292. const vector = array[ i ];
  7293. value[ index ] = vector.r;
  7294. value[ index + 1 ] = vector.g;
  7295. value[ index + 2 ] = vector.b || 0;
  7296. //value[ index + 3 ] = vector.a || 0;
  7297. }
  7298. } else if ( elementType === 'mat2' ) {
  7299. for ( let i = 0; i < array.length; i ++ ) {
  7300. const index = i * 4;
  7301. const matrix = array[ i ];
  7302. value[ index ] = matrix.elements[ 0 ];
  7303. value[ index + 1 ] = matrix.elements[ 1 ];
  7304. value[ index + 2 ] = matrix.elements[ 2 ];
  7305. value[ index + 3 ] = matrix.elements[ 3 ];
  7306. }
  7307. } else if ( elementType === 'mat3' ) {
  7308. for ( let i = 0; i < array.length; i ++ ) {
  7309. const index = i * 16;
  7310. const matrix = array[ i ];
  7311. value[ index ] = matrix.elements[ 0 ];
  7312. value[ index + 1 ] = matrix.elements[ 1 ];
  7313. value[ index + 2 ] = matrix.elements[ 2 ];
  7314. value[ index + 4 ] = matrix.elements[ 3 ];
  7315. value[ index + 5 ] = matrix.elements[ 4 ];
  7316. value[ index + 6 ] = matrix.elements[ 5 ];
  7317. value[ index + 8 ] = matrix.elements[ 6 ];
  7318. value[ index + 9 ] = matrix.elements[ 7 ];
  7319. value[ index + 10 ] = matrix.elements[ 8 ];
  7320. value[ index + 15 ] = 1;
  7321. }
  7322. } else if ( elementType === 'mat4' ) {
  7323. for ( let i = 0; i < array.length; i ++ ) {
  7324. const index = i * 16;
  7325. const matrix = array[ i ];
  7326. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7327. value[ index + i ] = matrix.elements[ i ];
  7328. }
  7329. }
  7330. } else {
  7331. for ( let i = 0; i < array.length; i ++ ) {
  7332. const index = i * 4;
  7333. const vector = array[ i ];
  7334. value[ index ] = vector.x;
  7335. value[ index + 1 ] = vector.y;
  7336. value[ index + 2 ] = vector.z || 0;
  7337. value[ index + 3 ] = vector.w || 0;
  7338. }
  7339. }
  7340. }
  7341. /**
  7342. * Implement the value buffer creation based on the array data.
  7343. *
  7344. * @param {NodeBuilder} builder - A reference to the current node builder.
  7345. * @return {null}
  7346. */
  7347. setup( builder ) {
  7348. const length = this.array.length;
  7349. const elementType = this.elementType;
  7350. let arrayType = Float32Array;
  7351. const paddedType = this.paddedType;
  7352. const paddedElementLength = builder.getTypeLength( paddedType );
  7353. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7354. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7355. this.value = new arrayType( length * paddedElementLength );
  7356. this.bufferCount = length;
  7357. this.bufferType = paddedType;
  7358. return super.setup( builder );
  7359. }
  7360. /**
  7361. * Overwrites the default `element()` method to provide element access
  7362. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7363. *
  7364. * @param {IndexNode} indexNode - The index node.
  7365. * @return {UniformArrayElementNode}
  7366. */
  7367. element( indexNode ) {
  7368. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7369. }
  7370. }
  7371. /**
  7372. * TSL function for creating an uniform array node.
  7373. *
  7374. * @function
  7375. * @param {Array<Any>} values - Array-like data.
  7376. * @param {String?} nodeType - The data type of the array elements.
  7377. * @returns {UniformArrayNode}
  7378. */
  7379. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7380. /**
  7381. * @function
  7382. * @deprecated since r168. Use {@link uniformArray} instead.
  7383. *
  7384. * @param {Array<Any>} values - Array-like data.
  7385. * @param {String} nodeType - The data type of the array elements.
  7386. * @returns {UniformArrayNode}
  7387. */
  7388. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7389. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7390. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7391. };
  7392. /** @module Camera **/
  7393. /**
  7394. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7395. *
  7396. * @type {UniformNode<uint>}
  7397. */
  7398. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7399. /**
  7400. * TSL object that represents the `near` value of the camera used for the current render.
  7401. *
  7402. * @type {UniformNode<float>}
  7403. */
  7404. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7405. /**
  7406. * TSL object that represents the `far` value of the camera used for the current render.
  7407. *
  7408. * @type {UniformNode<float>}
  7409. */
  7410. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7411. /**
  7412. * TSL object that represents the projection matrix of the camera used for the current render.
  7413. *
  7414. * @type {UniformNode<mat4>}
  7415. */
  7416. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7417. let cameraProjectionMatrix;
  7418. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7419. const matrices = [];
  7420. for ( const subCamera of camera.cameras ) {
  7421. matrices.push( subCamera.projectionMatrix );
  7422. }
  7423. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7424. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7425. } else {
  7426. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7427. }
  7428. return cameraProjectionMatrix;
  7429. } ).once() )();
  7430. /**
  7431. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7432. *
  7433. * @type {UniformNode<mat4>}
  7434. */
  7435. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7436. /**
  7437. * TSL object that represents the view matrix of the camera used for the current render.
  7438. *
  7439. * @type {UniformNode<mat4>}
  7440. */
  7441. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7442. let cameraViewMatrix;
  7443. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7444. const matrices = [];
  7445. for ( const subCamera of camera.cameras ) {
  7446. matrices.push( subCamera.matrixWorldInverse );
  7447. }
  7448. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7449. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7450. } else {
  7451. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7452. }
  7453. return cameraViewMatrix;
  7454. } ).once() )();
  7455. /**
  7456. * TSL object that represents the world matrix of the camera used for the current render.
  7457. *
  7458. * @type {UniformNode<mat4>}
  7459. */
  7460. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7461. /**
  7462. * TSL object that represents the normal matrix of the camera used for the current render.
  7463. *
  7464. * @type {UniformNode<mat3>}
  7465. */
  7466. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7467. /**
  7468. * TSL object that represents the position in world space of the camera used for the current render.
  7469. *
  7470. * @type {UniformNode<vec3>}
  7471. */
  7472. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7473. /** @module Object3DNode **/
  7474. /**
  7475. * This node can be used to access transformation related metrics of 3D objects.
  7476. * Depending on the selected scope, a different metric is represented as a uniform
  7477. * in the shader. The following scopes are supported:
  7478. *
  7479. * - `POSITION`: The object's position in world space.
  7480. * - `VIEW_POSITION`: The object's position in view/camera space.
  7481. * - `DIRECTION`: The object's direction in world space.
  7482. * - `SCALE`: The object's scale in world space.
  7483. * - `WORLD_MATRIX`: The object's matrix in world space.
  7484. *
  7485. * @augments Node
  7486. */
  7487. class Object3DNode extends Node {
  7488. static get type() {
  7489. return 'Object3DNode';
  7490. }
  7491. /**
  7492. * Constructs a new object 3D node.
  7493. *
  7494. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7495. * @param {Object3D?} [object3d=null] - The 3D object.
  7496. */
  7497. constructor( scope, object3d = null ) {
  7498. super();
  7499. /**
  7500. * The node reports a different type of transformation depending on the scope.
  7501. *
  7502. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7503. */
  7504. this.scope = scope;
  7505. /**
  7506. * The 3D object.
  7507. *
  7508. * @type {Object3D?}
  7509. * @default null
  7510. */
  7511. this.object3d = object3d;
  7512. /**
  7513. * Overwritten since this type of node is updated per object.
  7514. *
  7515. * @type {String}
  7516. * @default 'object'
  7517. */
  7518. this.updateType = NodeUpdateType.OBJECT;
  7519. /**
  7520. * Holds the value of the node as a uniform.
  7521. *
  7522. * @private
  7523. * @type {UniformNode}
  7524. */
  7525. this._uniformNode = new UniformNode( null );
  7526. }
  7527. /**
  7528. * Overwritten since the node type is inferred from the scope.
  7529. *
  7530. * @return {String} The node type.
  7531. */
  7532. getNodeType() {
  7533. const scope = this.scope;
  7534. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7535. return 'mat4';
  7536. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7537. return 'vec3';
  7538. }
  7539. }
  7540. /**
  7541. * Updates the uniform value depending on the scope.
  7542. *
  7543. * @param {NodeFrame} frame - The current node frame.
  7544. */
  7545. update( frame ) {
  7546. const object = this.object3d;
  7547. const uniformNode = this._uniformNode;
  7548. const scope = this.scope;
  7549. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7550. uniformNode.value = object.matrixWorld;
  7551. } else if ( scope === Object3DNode.POSITION ) {
  7552. uniformNode.value = uniformNode.value || new Vector3();
  7553. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7554. } else if ( scope === Object3DNode.SCALE ) {
  7555. uniformNode.value = uniformNode.value || new Vector3();
  7556. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7557. } else if ( scope === Object3DNode.DIRECTION ) {
  7558. uniformNode.value = uniformNode.value || new Vector3();
  7559. object.getWorldDirection( uniformNode.value );
  7560. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7561. const camera = frame.camera;
  7562. uniformNode.value = uniformNode.value || new Vector3();
  7563. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7564. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7565. }
  7566. }
  7567. /**
  7568. * Generates the code snippet of the uniform node. The node type of the uniform
  7569. * node also depends on the selected scope.
  7570. *
  7571. * @param {NodeBuilder} builder - The current node builder.
  7572. * @return {String} The generated code snippet.
  7573. */
  7574. generate( builder ) {
  7575. const scope = this.scope;
  7576. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7577. this._uniformNode.nodeType = 'mat4';
  7578. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7579. this._uniformNode.nodeType = 'vec3';
  7580. }
  7581. return this._uniformNode.build( builder );
  7582. }
  7583. serialize( data ) {
  7584. super.serialize( data );
  7585. data.scope = this.scope;
  7586. }
  7587. deserialize( data ) {
  7588. super.deserialize( data );
  7589. this.scope = data.scope;
  7590. }
  7591. }
  7592. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7593. Object3DNode.POSITION = 'position';
  7594. Object3DNode.SCALE = 'scale';
  7595. Object3DNode.VIEW_POSITION = 'viewPosition';
  7596. Object3DNode.DIRECTION = 'direction';
  7597. /**
  7598. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7599. *
  7600. * @function
  7601. * @param {Object3D?} [object3d=null] - The 3D object.
  7602. * @returns {Object3DNode<vec3>}
  7603. */
  7604. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7605. /**
  7606. * TSL function for creating an object 3D node that represents the object's world matrix.
  7607. *
  7608. * @function
  7609. * @param {Object3D?} [object3d=null] - The 3D object.
  7610. * @returns {Object3DNode<mat4>}
  7611. */
  7612. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7613. /**
  7614. * TSL function for creating an object 3D node that represents the object's position in world space.
  7615. *
  7616. * @function
  7617. * @param {Object3D?} [object3d=null] - The 3D object.
  7618. * @returns {Object3DNode<vec3>}
  7619. */
  7620. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7621. /**
  7622. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7623. *
  7624. * @function
  7625. * @param {Object3D?} [object3d=null] - The 3D object.
  7626. * @returns {Object3DNode<vec3>}
  7627. */
  7628. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7629. /**
  7630. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7631. *
  7632. * @function
  7633. * @param {Object3D?} [object3d=null] - The 3D object.
  7634. * @returns {Object3DNode<vec3>}
  7635. */
  7636. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7637. /** @module ModelNode **/
  7638. /**
  7639. * This type of node is a specialized version of `Object3DNode`
  7640. * with larger set of model related metrics. Unlike `Object3DNode`,
  7641. * `ModelNode` extracts the reference to the 3D object from the
  7642. * current node frame state.
  7643. *
  7644. * @augments module:Object3DNode~Object3DNode
  7645. */
  7646. class ModelNode extends Object3DNode {
  7647. static get type() {
  7648. return 'ModelNode';
  7649. }
  7650. /**
  7651. * Constructs a new object model node.
  7652. *
  7653. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7654. */
  7655. constructor( scope ) {
  7656. super( scope );
  7657. }
  7658. /**
  7659. * Extracts the model reference from the frame state and then
  7660. * updates the uniform value depending on the scope.
  7661. *
  7662. * @param {NodeFrame} frame - The current node frame.
  7663. */
  7664. update( frame ) {
  7665. this.object3d = frame.object;
  7666. super.update( frame );
  7667. }
  7668. }
  7669. /**
  7670. * TSL object that represents the object's direction in world space.
  7671. *
  7672. * @type {ModelNode<vec3>}
  7673. */
  7674. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7675. /**
  7676. * TSL object that represents the object's world matrix.
  7677. *
  7678. * @type {ModelNode<mat4>}
  7679. */
  7680. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7681. /**
  7682. * TSL object that represents the object's position in world space.
  7683. *
  7684. * @type {ModelNode<vec3>}
  7685. */
  7686. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7687. /**
  7688. * TSL object that represents the object's scale in world space.
  7689. *
  7690. * @type {ModelNode<vec3>}
  7691. */
  7692. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7693. /**
  7694. * TSL object that represents the object's position in view/camera space.
  7695. *
  7696. * @type {ModelNode<vec3>}
  7697. */
  7698. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7699. /**
  7700. * TSL object that represents the object's normal matrix.
  7701. *
  7702. * @type {UniformNode<mat3>}
  7703. */
  7704. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7705. /**
  7706. * TSL object that represents the object's inverse world matrix.
  7707. *
  7708. * @type {UniformNode<mat4>}
  7709. */
  7710. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7711. /**
  7712. * TSL object that represents the object's model view matrix.
  7713. *
  7714. * @type {Node<mat4>}
  7715. */
  7716. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7717. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7718. } ).once() )().toVar( 'modelViewMatrix' );
  7719. // GPU Precision
  7720. /**
  7721. * TSL object that represents the object's model view in `mediump` precision.
  7722. *
  7723. * @type {Node<mat4>}
  7724. */
  7725. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7726. // CPU Precision
  7727. /**
  7728. * TSL object that represents the object's model view in `highp` precision
  7729. * which is achieved by computing the matrix in JS and not in the shader.
  7730. *
  7731. * @type {Node<mat4>}
  7732. */
  7733. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7734. builder.context.isHighPrecisionModelViewMatrix = true;
  7735. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7736. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7737. } );
  7738. } ).once() )().toVar( 'highpModelViewMatrix' );
  7739. /**
  7740. * TSL object that represents the object's model normal view in `highp` precision
  7741. * which is achieved by computing the matrix in JS and not in the shader.
  7742. *
  7743. * @type {Node<mat3>}
  7744. */
  7745. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7746. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7747. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7748. if ( isHighPrecisionModelViewMatrix !== true ) {
  7749. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7750. }
  7751. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7752. } );
  7753. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7754. /** @module Position **/
  7755. /**
  7756. * TSL object that represents the position attribute of the current rendered object.
  7757. *
  7758. * @type {AttributeNode<vec3>}
  7759. */
  7760. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7761. /**
  7762. * TSL object that represents the vertex position in local space of the current rendered object.
  7763. *
  7764. * @type {AttributeNode<vec3>}
  7765. */
  7766. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  7767. /**
  7768. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7769. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7770. *
  7771. * @type {AttributeNode<vec3>}
  7772. */
  7773. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  7774. /**
  7775. * TSL object that represents the vertex position in world space of the current rendered object.
  7776. *
  7777. * @type {VaryingNode<vec3>}
  7778. */
  7779. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7780. /**
  7781. * TSL object that represents the position world direction of the current rendered object.
  7782. *
  7783. * @type {Node<vec3>}
  7784. */
  7785. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7786. /**
  7787. * TSL object that represents the vertex position in view space of the current rendered object.
  7788. *
  7789. * @type {VaryingNode<vec3>}
  7790. */
  7791. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7792. return builder.context.setupPositionView();
  7793. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7794. /**
  7795. * TSL object that represents the position view direction of the current rendered object.
  7796. *
  7797. * @type {VaryingNode<vec3>}
  7798. */
  7799. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7800. /** @module FrontFacingNode **/
  7801. /**
  7802. * This node can be used to evaluate whether a primitive is front or back facing.
  7803. *
  7804. * @augments Node
  7805. */
  7806. class FrontFacingNode extends Node {
  7807. static get type() {
  7808. return 'FrontFacingNode';
  7809. }
  7810. /**
  7811. * Constructs a new front facing node.
  7812. */
  7813. constructor() {
  7814. super( 'bool' );
  7815. /**
  7816. * This flag can be used for type testing.
  7817. *
  7818. * @type {Boolean}
  7819. * @readonly
  7820. * @default true
  7821. */
  7822. this.isFrontFacingNode = true;
  7823. }
  7824. generate( builder ) {
  7825. const { renderer, material } = builder;
  7826. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7827. if ( material.side === BackSide ) {
  7828. return 'false';
  7829. }
  7830. }
  7831. return builder.getFrontFacing();
  7832. }
  7833. }
  7834. /**
  7835. * TSL object that represents whether a primitive is front or back facing
  7836. *
  7837. * @type {FrontFacingNode<bool>}
  7838. */
  7839. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7840. /**
  7841. * TSL object that represents the front facing status as a number instead of a bool.
  7842. * `1` means front facing, `-1` means back facing.
  7843. *
  7844. * @type {Node<float>}
  7845. */
  7846. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7847. /** @module Normal **/
  7848. /**
  7849. * TSL object that represents the normal attribute of the current rendered object.
  7850. *
  7851. * @type {Node<vec3>}
  7852. */
  7853. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7854. /**
  7855. * TSL object that represents the vertex normal in local space of the current rendered object.
  7856. *
  7857. * @type {Node<vec3>}
  7858. */
  7859. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7860. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7861. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7862. return vec3( 0, 1, 0 );
  7863. }
  7864. return normalGeometry;
  7865. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7866. /**
  7867. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7868. *
  7869. * @type {Node<vec3>}
  7870. */
  7871. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7872. /**
  7873. * TSL object that represents the vertex normal in view space of the current rendered object.
  7874. *
  7875. * @type {Node<vec3>}
  7876. */
  7877. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7878. let node;
  7879. if ( builder.material.flatShading === true ) {
  7880. node = normalFlat;
  7881. } else {
  7882. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7883. }
  7884. return node;
  7885. }, 'vec3' ).once() )().toVar( 'normalView' );
  7886. /**
  7887. * TSL object that represents the vertex normal in world space of the current rendered object.
  7888. *
  7889. * @type {Node<vec3>}
  7890. */
  7891. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7892. /**
  7893. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7894. *
  7895. * @type {Node<vec3>}
  7896. */
  7897. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7898. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7899. return builder.context.setupNormal().context( { getUV: null } );
  7900. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7901. /**
  7902. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7903. *
  7904. * @type {Node<vec3>}
  7905. */
  7906. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7907. /**
  7908. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7909. *
  7910. * @type {Node<vec3>}
  7911. */
  7912. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7913. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7914. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  7915. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7916. /**
  7917. * Transforms the normal with the given matrix.
  7918. *
  7919. * @function
  7920. * @param {Node<vec3>} normal - The normal.
  7921. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7922. * @return {Node<vec3>} The transformed normal.
  7923. */
  7924. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7925. const m = mat3( matrix );
  7926. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7927. return m.mul( transformedNormal ).xyz;
  7928. } );
  7929. /**
  7930. * Transforms the given normal from local to view space.
  7931. *
  7932. * @function
  7933. * @param {Node<vec3>} normal - The normal.
  7934. * @param {NodeBuilder} builder - The current node builder.
  7935. * @return {Node<vec3>} The transformed normal.
  7936. */
  7937. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7938. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7939. if ( modelNormalViewMatrix !== null ) {
  7940. return modelNormalViewMatrix.transformDirection( normal );
  7941. }
  7942. //
  7943. const transformedNormal = modelNormalMatrix.mul( normal );
  7944. return cameraViewMatrix.transformDirection( transformedNormal );
  7945. } );
  7946. /** @module MaterialProperties **/
  7947. /**
  7948. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7949. *
  7950. * @type {UniformNode<float>}
  7951. */
  7952. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7953. /** @module ReflectVector **/
  7954. /**
  7955. * The reflect vector in view space.
  7956. *
  7957. * @type {Node<vec3>}
  7958. */
  7959. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7960. /**
  7961. * The refract vector in view space.
  7962. *
  7963. * @type {Node<vec3>}
  7964. */
  7965. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7966. /**
  7967. * Used for sampling cube maps when using cube reflection mapping.
  7968. *
  7969. * @type {Node<vec3>}
  7970. */
  7971. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7972. /**
  7973. * Used for sampling cube maps when using cube refraction mapping.
  7974. *
  7975. * @type {Node<vec3>}
  7976. */
  7977. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7978. /** @module CubeTextureNode **/
  7979. /**
  7980. * This type of uniform node represents a cube texture.
  7981. *
  7982. * @augments module:TextureNode~TextureNode
  7983. */
  7984. class CubeTextureNode extends TextureNode {
  7985. static get type() {
  7986. return 'CubeTextureNode';
  7987. }
  7988. /**
  7989. * Constructs a new cube texture node.
  7990. *
  7991. * @param {CubeTexture} value - The cube texture.
  7992. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7993. * @param {Node<int>?} [levelNode=null] - The level node.
  7994. * @param {Node<float>?} [biasNode=null] - The bias node.
  7995. */
  7996. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7997. super( value, uvNode, levelNode, biasNode );
  7998. /**
  7999. * This flag can be used for type testing.
  8000. *
  8001. * @type {Boolean}
  8002. * @readonly
  8003. * @default true
  8004. */
  8005. this.isCubeTextureNode = true;
  8006. }
  8007. /**
  8008. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8009. *
  8010. * @param {NodeBuilder} builder - The current node builder.
  8011. * @return {String} The input type.
  8012. */
  8013. getInputType( /*builder*/ ) {
  8014. return 'cubeTexture';
  8015. }
  8016. /**
  8017. * Returns a default uvs based on the mapping type of the cube texture.
  8018. *
  8019. * @return {Node<vec3>} The default uv attribute.
  8020. */
  8021. getDefaultUV() {
  8022. const texture = this.value;
  8023. if ( texture.mapping === CubeReflectionMapping ) {
  8024. return reflectVector;
  8025. } else if ( texture.mapping === CubeRefractionMapping ) {
  8026. return refractVector;
  8027. } else {
  8028. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8029. return vec3( 0, 0, 0 );
  8030. }
  8031. }
  8032. /**
  8033. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8034. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8035. *
  8036. * @param {Boolean} value - The update toggle.
  8037. */
  8038. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8039. /**
  8040. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8041. * to modify the uv node for correct sampling.
  8042. *
  8043. * @param {NodeBuilder} builder - The current node builder.
  8044. * @param {Node} uvNode - The uv node to setup.
  8045. * @return {Node} The updated uv node.
  8046. */
  8047. setupUV( builder, uvNode ) {
  8048. const texture = this.value;
  8049. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8050. return vec3( uvNode.x.negate(), uvNode.yz );
  8051. } else {
  8052. return uvNode;
  8053. }
  8054. }
  8055. /**
  8056. * Generates the uv code snippet.
  8057. *
  8058. * @param {NodeBuilder} builder - The current node builder.
  8059. * @param {Node} cubeUV - The uv node to generate code for.
  8060. * @return {String} The generated code snippet.
  8061. */
  8062. generateUV( builder, cubeUV ) {
  8063. return cubeUV.build( builder, 'vec3' );
  8064. }
  8065. }
  8066. /**
  8067. * TSL function for creating a cube texture node.
  8068. *
  8069. * @function
  8070. * @param {CubeTexture} value - The cube texture.
  8071. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  8072. * @param {Node<int>?} [levelNode=null] - The level node.
  8073. * @param {Node<float>?} [biasNode=null] - The bias node.
  8074. * @returns {CubeTextureNode}
  8075. */
  8076. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  8077. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8078. /** @module ReferenceNode **/
  8079. /**
  8080. * This class is only relevant if the referenced property is array-like.
  8081. * In this case, `ReferenceElementNode` allows to refer to a specific
  8082. * element inside the data structure via an index.
  8083. *
  8084. * @augments ArrayElementNode
  8085. */
  8086. class ReferenceElementNode extends ArrayElementNode {
  8087. static get type() {
  8088. return 'ReferenceElementNode';
  8089. }
  8090. /**
  8091. * Constructs a new reference element node.
  8092. *
  8093. * @param {ReferenceNode?} referenceNode - The reference node.
  8094. * @param {Node} indexNode - The index node that defines the element access.
  8095. */
  8096. constructor( referenceNode, indexNode ) {
  8097. super( referenceNode, indexNode );
  8098. /**
  8099. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  8100. * property references to the current node.
  8101. *
  8102. * @type {ReferenceNode?}
  8103. * @default null
  8104. */
  8105. this.referenceNode = referenceNode;
  8106. /**
  8107. * This flag can be used for type testing.
  8108. *
  8109. * @type {Boolean}
  8110. * @readonly
  8111. * @default true
  8112. */
  8113. this.isReferenceElementNode = true;
  8114. }
  8115. /**
  8116. * This method is overwritten since the node type is inferred from
  8117. * the uniform type of the reference node.
  8118. *
  8119. * @return {String} The node type.
  8120. */
  8121. getNodeType() {
  8122. return this.referenceNode.uniformType;
  8123. }
  8124. generate( builder ) {
  8125. const snippet = super.generate( builder );
  8126. const arrayType = this.referenceNode.getNodeType();
  8127. const elementType = this.getNodeType();
  8128. return builder.format( snippet, arrayType, elementType );
  8129. }
  8130. }
  8131. /**
  8132. * This type of node establishes a reference to a property of another object.
  8133. * In this way, the value of the node is automatically linked to the value of
  8134. * referenced object. Reference nodes internally represent the linked value
  8135. * as a uniform.
  8136. *
  8137. * @augments Node
  8138. */
  8139. class ReferenceNode extends Node {
  8140. static get type() {
  8141. return 'ReferenceNode';
  8142. }
  8143. /**
  8144. * Constructs a new reference node.
  8145. *
  8146. * @param {String} property - The name of the property the node refers to.
  8147. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  8148. * @param {Object?} [object=null] - The object the property belongs to.
  8149. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8150. */
  8151. constructor( property, uniformType, object = null, count = null ) {
  8152. super();
  8153. /**
  8154. * The name of the property the node refers to.
  8155. *
  8156. * @type {String}
  8157. */
  8158. this.property = property;
  8159. /**
  8160. * The uniform type that should be used to represent the property value.
  8161. *
  8162. * @type {String}
  8163. */
  8164. this.uniformType = uniformType;
  8165. /**
  8166. * The object the property belongs to.
  8167. *
  8168. * @type {Object?}
  8169. * @default null
  8170. */
  8171. this.object = object;
  8172. /**
  8173. * When the linked property is an array, this parameter defines its length.
  8174. *
  8175. * @type {Number?}
  8176. * @default null
  8177. */
  8178. this.count = count;
  8179. /**
  8180. * The property name might have dots so nested properties can be referred.
  8181. * The hierarchy of the names is stored inside this array.
  8182. *
  8183. * @type {Array<String>}
  8184. */
  8185. this.properties = property.split( '.' );
  8186. /**
  8187. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  8188. * since the final reference might be updated from calling code.
  8189. *
  8190. * @type {Object?}
  8191. * @default null
  8192. */
  8193. this.reference = object;
  8194. /**
  8195. * The uniform node that holds the value of the reference node.
  8196. *
  8197. * @type {UniformNode}
  8198. * @default null
  8199. */
  8200. this.node = null;
  8201. /**
  8202. * The uniform group of the internal uniform.
  8203. *
  8204. * @type {UniformGroupNode}
  8205. * @default null
  8206. */
  8207. this.group = null;
  8208. /**
  8209. * An optional label of the internal uniform node.
  8210. *
  8211. * @type {String?}
  8212. * @default null
  8213. */
  8214. this.name = null;
  8215. /**
  8216. * Overwritten since reference nodes are updated per object.
  8217. *
  8218. * @type {String}
  8219. * @default 'object'
  8220. */
  8221. this.updateType = NodeUpdateType.OBJECT;
  8222. }
  8223. /**
  8224. * When the referred property is array-like, this method can be used
  8225. * to access elements via an index node.
  8226. *
  8227. * @param {IndexNode} indexNode - indexNode.
  8228. * @return {ReferenceElementNode} A reference to an element.
  8229. */
  8230. element( indexNode ) {
  8231. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8232. }
  8233. /**
  8234. * Sets the uniform group for this reference node.
  8235. *
  8236. * @param {UniformGroupNode} group - The uniform group to set.
  8237. * @return {ReferenceNode} A reference to this node.
  8238. */
  8239. setGroup( group ) {
  8240. this.group = group;
  8241. return this;
  8242. }
  8243. /**
  8244. * Sets the label for the internal uniform.
  8245. *
  8246. * @param {String} name - The label to set.
  8247. * @return {ReferenceNode} A reference to this node.
  8248. */
  8249. label( name ) {
  8250. this.name = name;
  8251. return this;
  8252. }
  8253. /**
  8254. * Sets the node type which automatically defines the internal
  8255. * uniform type.
  8256. *
  8257. * @param {String} uniformType - The type to set.
  8258. */
  8259. setNodeType( uniformType ) {
  8260. let node = null;
  8261. if ( this.count !== null ) {
  8262. node = buffer( null, uniformType, this.count );
  8263. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8264. node = uniformArray( null, uniformType );
  8265. } else if ( uniformType === 'texture' ) {
  8266. node = texture( null );
  8267. } else if ( uniformType === 'cubeTexture' ) {
  8268. node = cubeTexture( null );
  8269. } else {
  8270. node = uniform( null, uniformType );
  8271. }
  8272. if ( this.group !== null ) {
  8273. node.setGroup( this.group );
  8274. }
  8275. if ( this.name !== null ) node.label( this.name );
  8276. this.node = node.getSelf();
  8277. }
  8278. /**
  8279. * This method is overwritten since the node type is inferred from
  8280. * the type of the reference node.
  8281. *
  8282. * @param {NodeBuilder} builder - The current node builder.
  8283. * @return {String} The node type.
  8284. */
  8285. getNodeType( builder ) {
  8286. if ( this.node === null ) {
  8287. this.updateReference( builder );
  8288. this.updateValue();
  8289. }
  8290. return this.node.getNodeType( builder );
  8291. }
  8292. /**
  8293. * Returns the property value from the given referred object.
  8294. *
  8295. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8296. * @return {Any} The value.
  8297. */
  8298. getValueFromReference( object = this.reference ) {
  8299. const { properties } = this;
  8300. let value = object[ properties[ 0 ] ];
  8301. for ( let i = 1; i < properties.length; i ++ ) {
  8302. value = value[ properties[ i ] ];
  8303. }
  8304. return value;
  8305. }
  8306. /**
  8307. * Allows to update the reference based on the given state. The state is only
  8308. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  8309. *
  8310. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8311. * @return {Object} The updated reference.
  8312. */
  8313. updateReference( state ) {
  8314. this.reference = this.object !== null ? this.object : state.object;
  8315. return this.reference;
  8316. }
  8317. /**
  8318. * The output of the reference node is the internal uniform node.
  8319. *
  8320. * @param {NodeBuilder} builder - The current node builder.
  8321. * @return {UniformNode} The output node.
  8322. */
  8323. setup( /* builder */ ) {
  8324. this.updateValue();
  8325. return this.node;
  8326. }
  8327. /**
  8328. * Overwritten to to update the internal uniform value.
  8329. *
  8330. * @param {NodeFrame} frame - A reference to the current node frame.
  8331. */
  8332. update( /*frame*/ ) {
  8333. this.updateValue();
  8334. }
  8335. /**
  8336. * Retrieves the value from the referred object property and uses it
  8337. * to updated the internal uniform.
  8338. */
  8339. updateValue() {
  8340. if ( this.node === null ) this.setNodeType( this.uniformType );
  8341. const value = this.getValueFromReference();
  8342. if ( Array.isArray( value ) ) {
  8343. this.node.array = value;
  8344. } else {
  8345. this.node.value = value;
  8346. }
  8347. }
  8348. }
  8349. /**
  8350. * TSL function for creating a reference node.
  8351. *
  8352. * @function
  8353. * @param {String} name - The name of the property the node refers to.
  8354. * @param {String} type - The uniform type that should be used to represent the property value.
  8355. * @param {Object} object - The object the property belongs to.
  8356. * @returns {ReferenceNode}
  8357. */
  8358. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8359. /**
  8360. * TSL function for creating a reference node. Use this function if you want need a reference
  8361. * to an array-like property that should be represented as a uniform buffer.
  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 {Number} count - The number of value inside the array-like object.
  8367. * @param {Object} object - An array-like object the property belongs to.
  8368. * @returns {ReferenceNode}
  8369. */
  8370. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8371. /** @module MaterialReferenceNode **/
  8372. /**
  8373. * This node is a special type of reference node which is intended
  8374. * for linking material properties with node values.
  8375. * ```js
  8376. * const opacityNode = materialReference( 'opacity', 'float', material );
  8377. * ```
  8378. * When changing `material.opacity`, the node value of `opacityNode` will
  8379. * automatically be updated.
  8380. *
  8381. * @augments module:ReferenceNode~ReferenceNode
  8382. */
  8383. class MaterialReferenceNode extends ReferenceNode {
  8384. static get type() {
  8385. return 'MaterialReferenceNode';
  8386. }
  8387. /**
  8388. * Constructs a new material reference node.
  8389. *
  8390. * @param {String} property - The name of the property the node refers to.
  8391. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8392. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8393. * the node refers to the material of the current rendered object.
  8394. */
  8395. constructor( property, inputType, material = null ) {
  8396. super( property, inputType, material );
  8397. /**
  8398. * The material the property belongs to. When no material is set,
  8399. * the node refers to the material of the current rendered object.
  8400. *
  8401. * @type {Material?}
  8402. * @default null
  8403. */
  8404. this.material = material;
  8405. /**
  8406. * This flag can be used for type testing.
  8407. *
  8408. * @type {Boolean}
  8409. * @readonly
  8410. * @default true
  8411. */
  8412. this.isMaterialReferenceNode = true;
  8413. }
  8414. /**
  8415. * Updates the reference based on the given state. The state is only evaluated
  8416. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8417. *
  8418. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8419. * @return {Object} The updated reference.
  8420. */
  8421. updateReference( state ) {
  8422. this.reference = this.material !== null ? this.material : state.material;
  8423. return this.reference;
  8424. }
  8425. }
  8426. /**
  8427. * TSL function for creating a material reference node.
  8428. *
  8429. * @function
  8430. * @param {String} name - The name of the property the node refers to.
  8431. * @param {String} type - The uniform type that should be used to represent the property value.
  8432. * @param {Material?} [material=null] - The material the property belongs to.
  8433. * When no material is set, the node refers to the material of the current rendered object.
  8434. * @returns {MaterialReferenceNode}
  8435. */
  8436. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8437. /** @module Tangent **/
  8438. /**
  8439. * TSL object that represents the tangent attribute of the current rendered object.
  8440. *
  8441. * @type {Node<vec4>}
  8442. */
  8443. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8444. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8445. builder.geometry.computeTangents();
  8446. }
  8447. return attribute( 'tangent', 'vec4' );
  8448. } )();
  8449. /**
  8450. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8451. *
  8452. * @type {Node<vec3>}
  8453. */
  8454. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8455. /**
  8456. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8457. *
  8458. * @type {Node<vec3>}
  8459. */
  8460. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8461. /**
  8462. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8463. *
  8464. * @type {Node<vec3>}
  8465. */
  8466. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8467. /**
  8468. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8469. *
  8470. * @type {Node<vec3>}
  8471. */
  8472. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8473. /**
  8474. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8475. *
  8476. * @type {Node<vec3>}
  8477. */
  8478. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8479. /** @module Bitangent **/
  8480. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8481. /**
  8482. * TSL object that represents the bitangent attribute of the current rendered object.
  8483. *
  8484. * @type {Node<vec3>}
  8485. */
  8486. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8487. /**
  8488. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8489. *
  8490. * @type {Node<vec3>}
  8491. */
  8492. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8493. /**
  8494. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8495. *
  8496. * @type {Node<vec4>}
  8497. */
  8498. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8499. /**
  8500. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8501. *
  8502. * @type {Node<vec4>}
  8503. */
  8504. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8505. /**
  8506. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8507. *
  8508. * @type {Node<vec4>}
  8509. */
  8510. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8511. /**
  8512. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8513. *
  8514. * @type {Node<vec4>}
  8515. */
  8516. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8517. /** @module AccessorsUtils **/
  8518. /**
  8519. * TSL object that represents the TBN matrix in view space.
  8520. *
  8521. * @type {Node<mat3>}
  8522. */
  8523. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8524. /**
  8525. * TSL object that represents the parallax direction.
  8526. *
  8527. * @type {Node<mat3>}
  8528. */
  8529. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8530. /**
  8531. * TSL function for computing parallax uv coordinates.
  8532. *
  8533. * @function
  8534. * @param {Node<vec2>} uv - A uv node.
  8535. * @param {Node<vec2>} scale - A scale node.
  8536. * @returns {Node<vec2>} Parallax uv coordinates.
  8537. */
  8538. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8539. /**
  8540. * TSL function for computing bent normals.
  8541. *
  8542. * @function
  8543. * @returns {Node<vec3>} Bent normals.
  8544. */
  8545. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8546. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8547. let bentNormal = anisotropyB.cross( positionViewDirection );
  8548. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8549. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8550. return bentNormal;
  8551. } )();
  8552. /** @module NormalMapNode **/
  8553. // Normal Mapping Without Precomputed Tangents
  8554. // http://www.thetenthplanet.de/archives/1180
  8555. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8556. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8557. const q0 = eye_pos.dFdx();
  8558. const q1 = eye_pos.dFdy();
  8559. const st0 = uv.dFdx();
  8560. const st1 = uv.dFdy();
  8561. const N = surf_norm; // normalized
  8562. const q1perp = q1.cross( N );
  8563. const q0perp = N.cross( q0 );
  8564. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8565. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8566. const det = T.dot( T ).max( B.dot( B ) );
  8567. const scale = faceDirection.mul( det.inverseSqrt() );
  8568. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8569. } );
  8570. /**
  8571. * This class can be used for applying normals maps to materials.
  8572. *
  8573. * ```js
  8574. * material.normalNode = normalMap( texture( normalTex ) );
  8575. * ```
  8576. *
  8577. * @augments TempNode
  8578. */
  8579. class NormalMapNode extends TempNode {
  8580. static get type() {
  8581. return 'NormalMapNode';
  8582. }
  8583. /**
  8584. * Constructs a new normal map node.
  8585. *
  8586. * @param {Node<vec3>} node - Represents the normal map data.
  8587. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8588. */
  8589. constructor( node, scaleNode = null ) {
  8590. super( 'vec3' );
  8591. /**
  8592. * Represents the normal map data.
  8593. *
  8594. * @type {Node<vec3>}
  8595. */
  8596. this.node = node;
  8597. /**
  8598. * Controls the intensity of the effect.
  8599. *
  8600. * @type {Node<vec2>?}
  8601. * @default null
  8602. */
  8603. this.scaleNode = scaleNode;
  8604. /**
  8605. * The normal map type.
  8606. *
  8607. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8608. * @default TangentSpaceNormalMap
  8609. */
  8610. this.normalMapType = TangentSpaceNormalMap;
  8611. }
  8612. setup( builder ) {
  8613. const { normalMapType, scaleNode } = this;
  8614. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8615. if ( scaleNode !== null ) {
  8616. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8617. }
  8618. let outputNode = null;
  8619. if ( normalMapType === ObjectSpaceNormalMap ) {
  8620. outputNode = transformNormalToView( normalMap );
  8621. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8622. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8623. if ( tangent === true ) {
  8624. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8625. } else {
  8626. outputNode = perturbNormal2Arb( {
  8627. eye_pos: positionView,
  8628. surf_norm: normalView,
  8629. mapN: normalMap,
  8630. uv: uv()
  8631. } );
  8632. }
  8633. }
  8634. return outputNode;
  8635. }
  8636. }
  8637. /**
  8638. * TSL function for creating a normal map node.
  8639. *
  8640. * @function
  8641. * @param {Node<vec3>} node - Represents the normal map data.
  8642. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8643. * @returns {NormalMapNode}
  8644. */
  8645. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8646. /** @module BumpMapNode **/
  8647. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8648. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8649. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8650. // It's used to preserve the same TextureNode instance
  8651. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8652. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8653. return vec2(
  8654. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8655. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8656. ).mul( bumpScale );
  8657. } );
  8658. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8659. const perturbNormalArb = Fn( ( inputs ) => {
  8660. const { surf_pos, surf_norm, dHdxy } = inputs;
  8661. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8662. const vSigmaX = surf_pos.dFdx().normalize();
  8663. const vSigmaY = surf_pos.dFdy().normalize();
  8664. const vN = surf_norm; // normalized
  8665. const R1 = vSigmaY.cross( vN );
  8666. const R2 = vN.cross( vSigmaX );
  8667. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8668. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8669. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8670. } );
  8671. /**
  8672. * This class can be used for applying bump maps to materials.
  8673. *
  8674. * ```js
  8675. * material.normalNode = bumpMap( texture( bumpTex ) );
  8676. * ```
  8677. *
  8678. * @augments TempNode
  8679. */
  8680. class BumpMapNode extends TempNode {
  8681. static get type() {
  8682. return 'BumpMapNode';
  8683. }
  8684. /**
  8685. * Constructs a new bump map node.
  8686. *
  8687. * @param {Node<float>} textureNode - Represents the bump map data.
  8688. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8689. */
  8690. constructor( textureNode, scaleNode = null ) {
  8691. super( 'vec3' );
  8692. /**
  8693. * Represents the bump map data.
  8694. *
  8695. * @type {Node<float>}
  8696. */
  8697. this.textureNode = textureNode;
  8698. /**
  8699. * Controls the intensity of the bump effect.
  8700. *
  8701. * @type {Node<float>?}
  8702. * @default null
  8703. */
  8704. this.scaleNode = scaleNode;
  8705. }
  8706. setup() {
  8707. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8708. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8709. return perturbNormalArb( {
  8710. surf_pos: positionView,
  8711. surf_norm: normalView,
  8712. dHdxy
  8713. } );
  8714. }
  8715. }
  8716. /**
  8717. * TSL function for creating a bump map node.
  8718. *
  8719. * @function
  8720. * @param {Node<float>} textureNode - Represents the bump map data.
  8721. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8722. * @returns {BumpMapNode}
  8723. */
  8724. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8725. /** @module MaterialNode **/
  8726. const _propertyCache = new Map();
  8727. /**
  8728. * This class should simplify the node access to material properties.
  8729. * It internal uses reference nodes to make sure changes to material
  8730. * properties are automatically reflected to predefined TSL objects
  8731. * like e.g. `materialColor`.
  8732. *
  8733. * @augments Node
  8734. */
  8735. class MaterialNode extends Node {
  8736. static get type() {
  8737. return 'MaterialNode';
  8738. }
  8739. /**
  8740. * Constructs a new material node.
  8741. *
  8742. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8743. */
  8744. constructor( scope ) {
  8745. super();
  8746. /**
  8747. * The scope defines what material property is referred by the node.
  8748. *
  8749. * @type {String}
  8750. */
  8751. this.scope = scope;
  8752. }
  8753. /**
  8754. * Returns a cached reference node for the given property and type.
  8755. *
  8756. * @param {String} property - The name of the material property.
  8757. * @param {String} type - The uniform type of the property.
  8758. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8759. */
  8760. getCache( property, type ) {
  8761. let node = _propertyCache.get( property );
  8762. if ( node === undefined ) {
  8763. node = materialReference( property, type );
  8764. _propertyCache.set( property, node );
  8765. }
  8766. return node;
  8767. }
  8768. /**
  8769. * Returns a float-typed material reference node for the given property name.
  8770. *
  8771. * @param {String} property - The name of the material property.
  8772. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8773. */
  8774. getFloat( property ) {
  8775. return this.getCache( property, 'float' );
  8776. }
  8777. /**
  8778. * Returns a color-typed material reference node for the given property name.
  8779. *
  8780. * @param {String} property - The name of the material property.
  8781. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8782. */
  8783. getColor( property ) {
  8784. return this.getCache( property, 'color' );
  8785. }
  8786. /**
  8787. * Returns a texture-typed material reference node for the given property name.
  8788. *
  8789. * @param {String} property - The name of the material property.
  8790. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8791. */
  8792. getTexture( property ) {
  8793. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8794. }
  8795. /**
  8796. * The node setup is done depending on the selected scope. Multiple material properties
  8797. * might be grouped into a single node composition if they logically belong together.
  8798. *
  8799. * @param {NodeBuilder} builder - The current node builder.
  8800. * @return {Node} The node representing the selected scope.
  8801. */
  8802. setup( builder ) {
  8803. const material = builder.context.material;
  8804. const scope = this.scope;
  8805. let node = null;
  8806. if ( scope === MaterialNode.COLOR ) {
  8807. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8808. if ( material.map && material.map.isTexture === true ) {
  8809. node = colorNode.mul( this.getTexture( 'map' ) );
  8810. } else {
  8811. node = colorNode;
  8812. }
  8813. } else if ( scope === MaterialNode.OPACITY ) {
  8814. const opacityNode = this.getFloat( scope );
  8815. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8816. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8817. } else {
  8818. node = opacityNode;
  8819. }
  8820. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8821. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8822. node = this.getTexture( 'specular' ).r;
  8823. } else {
  8824. node = float( 1 );
  8825. }
  8826. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8827. const specularIntensityNode = this.getFloat( scope );
  8828. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8829. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8830. } else {
  8831. node = specularIntensityNode;
  8832. }
  8833. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8834. const specularColorNode = this.getColor( scope );
  8835. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8836. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8837. } else {
  8838. node = specularColorNode;
  8839. }
  8840. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8841. const roughnessNode = this.getFloat( scope );
  8842. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8843. node = roughnessNode.mul( this.getTexture( scope ).g );
  8844. } else {
  8845. node = roughnessNode;
  8846. }
  8847. } else if ( scope === MaterialNode.METALNESS ) {
  8848. const metalnessNode = this.getFloat( scope );
  8849. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8850. node = metalnessNode.mul( this.getTexture( scope ).b );
  8851. } else {
  8852. node = metalnessNode;
  8853. }
  8854. } else if ( scope === MaterialNode.EMISSIVE ) {
  8855. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8856. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8857. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8858. node = emissiveNode.mul( this.getTexture( scope ) );
  8859. } else {
  8860. node = emissiveNode;
  8861. }
  8862. } else if ( scope === MaterialNode.NORMAL ) {
  8863. if ( material.normalMap ) {
  8864. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8865. node.normalMapType = material.normalMapType;
  8866. } else if ( material.bumpMap ) {
  8867. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8868. } else {
  8869. node = normalView;
  8870. }
  8871. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8872. const clearcoatNode = this.getFloat( scope );
  8873. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8874. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8875. } else {
  8876. node = clearcoatNode;
  8877. }
  8878. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8879. const clearcoatRoughnessNode = this.getFloat( scope );
  8880. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8881. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8882. } else {
  8883. node = clearcoatRoughnessNode;
  8884. }
  8885. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8886. if ( material.clearcoatNormalMap ) {
  8887. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8888. } else {
  8889. node = normalView;
  8890. }
  8891. } else if ( scope === MaterialNode.SHEEN ) {
  8892. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8893. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8894. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8895. } else {
  8896. node = sheenNode;
  8897. }
  8898. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8899. const sheenRoughnessNode = this.getFloat( scope );
  8900. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8901. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8902. } else {
  8903. node = sheenRoughnessNode;
  8904. }
  8905. node = node.clamp( 0.07, 1.0 );
  8906. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8907. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8908. const anisotropyPolar = this.getTexture( scope );
  8909. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8910. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8911. } else {
  8912. node = materialAnisotropyVector;
  8913. }
  8914. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8915. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8916. if ( material.iridescenceThicknessMap ) {
  8917. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8918. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8919. } else {
  8920. node = iridescenceThicknessMaximum;
  8921. }
  8922. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8923. const transmissionNode = this.getFloat( scope );
  8924. if ( material.transmissionMap ) {
  8925. node = transmissionNode.mul( this.getTexture( scope ).r );
  8926. } else {
  8927. node = transmissionNode;
  8928. }
  8929. } else if ( scope === MaterialNode.THICKNESS ) {
  8930. const thicknessNode = this.getFloat( scope );
  8931. if ( material.thicknessMap ) {
  8932. node = thicknessNode.mul( this.getTexture( scope ).g );
  8933. } else {
  8934. node = thicknessNode;
  8935. }
  8936. } else if ( scope === MaterialNode.IOR ) {
  8937. node = this.getFloat( scope );
  8938. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8939. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8940. } else if ( scope === MaterialNode.AO ) {
  8941. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8942. } else {
  8943. const outputType = this.getNodeType( builder );
  8944. node = this.getCache( scope, outputType );
  8945. }
  8946. return node;
  8947. }
  8948. }
  8949. MaterialNode.ALPHA_TEST = 'alphaTest';
  8950. MaterialNode.COLOR = 'color';
  8951. MaterialNode.OPACITY = 'opacity';
  8952. MaterialNode.SHININESS = 'shininess';
  8953. MaterialNode.SPECULAR = 'specular';
  8954. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8955. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8956. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8957. MaterialNode.REFLECTIVITY = 'reflectivity';
  8958. MaterialNode.ROUGHNESS = 'roughness';
  8959. MaterialNode.METALNESS = 'metalness';
  8960. MaterialNode.NORMAL = 'normal';
  8961. MaterialNode.CLEARCOAT = 'clearcoat';
  8962. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8963. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8964. MaterialNode.EMISSIVE = 'emissive';
  8965. MaterialNode.ROTATION = 'rotation';
  8966. MaterialNode.SHEEN = 'sheen';
  8967. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8968. MaterialNode.ANISOTROPY = 'anisotropy';
  8969. MaterialNode.IRIDESCENCE = 'iridescence';
  8970. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8971. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8972. MaterialNode.IOR = 'ior';
  8973. MaterialNode.TRANSMISSION = 'transmission';
  8974. MaterialNode.THICKNESS = 'thickness';
  8975. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8976. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8977. MaterialNode.LINE_SCALE = 'scale';
  8978. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8979. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8980. MaterialNode.LINE_WIDTH = 'linewidth';
  8981. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8982. MaterialNode.POINT_SIZE = 'size';
  8983. MaterialNode.DISPERSION = 'dispersion';
  8984. MaterialNode.LIGHT_MAP = 'light';
  8985. MaterialNode.AO = 'ao';
  8986. /**
  8987. * TSL object that represents alpha test of the current material.
  8988. *
  8989. * @type {Node<float>}
  8990. */
  8991. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8992. /**
  8993. * TSL object that represents the diffuse color of the current material.
  8994. * The value is composed via `color` * `map`.
  8995. *
  8996. * @type {Node<vec3>}
  8997. */
  8998. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8999. /**
  9000. * TSL object that represents the shininess of the current material.
  9001. *
  9002. * @type {Node<float>}
  9003. */
  9004. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9005. /**
  9006. * TSL object that represents the emissive color of the current material.
  9007. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9008. *
  9009. * @type {Node<vec3>}
  9010. */
  9011. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9012. /**
  9013. * TSL object that represents the opacity of the current material.
  9014. * The value is composed via `opacity` * `alphaMap`.
  9015. *
  9016. * @type {Node<float>}
  9017. */
  9018. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9019. /**
  9020. * TSL object that represents the specular of the current material.
  9021. *
  9022. * @type {Node<vec3>}
  9023. */
  9024. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9025. /**
  9026. * TSL object that represents the specular intensity of the current material.
  9027. * The value is composed via `specularIntensity` * `specularMap.a`.
  9028. *
  9029. * @type {Node<float>}
  9030. */
  9031. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9032. /**
  9033. * TSL object that represents the specular color of the current material.
  9034. * The value is composed via `specularColor` * `specularMap.rgb`.
  9035. *
  9036. * @type {Node<vec3>}
  9037. */
  9038. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9039. /**
  9040. * TSL object that represents the specular strength of the current material.
  9041. * The value is composed via `specularMap.r`.
  9042. *
  9043. * @type {Node<float>}
  9044. */
  9045. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9046. /**
  9047. * TSL object that represents the reflectivity of the current material.
  9048. *
  9049. * @type {Node<float>}
  9050. */
  9051. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9052. /**
  9053. * TSL object that represents the roughness of the current material.
  9054. * The value is composed via `roughness` * `roughnessMap.g`.
  9055. *
  9056. * @type {Node<float>}
  9057. */
  9058. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9059. /**
  9060. * TSL object that represents the metalness of the current material.
  9061. * The value is composed via `metalness` * `metalnessMap.b`.
  9062. *
  9063. * @type {Node<float>}
  9064. */
  9065. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9066. /**
  9067. * TSL object that represents the normal of the current material.
  9068. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9069. *
  9070. * @type {Node<vec3>}
  9071. */
  9072. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9073. /**
  9074. * TSL object that represents the clearcoat of the current material.
  9075. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9076. *
  9077. * @type {Node<float>}
  9078. */
  9079. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9080. /**
  9081. * TSL object that represents the clearcoat roughness of the current material.
  9082. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9083. *
  9084. * @type {Node<float>}
  9085. */
  9086. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9087. /**
  9088. * TSL object that represents the clearcoat normal of the current material.
  9089. * The value will be either `clearcoatNormalMap` or `normalView`.
  9090. *
  9091. * @type {Node<vec3>}
  9092. */
  9093. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9094. /**
  9095. * TSL object that represents the rotation of the current sprite material.
  9096. *
  9097. * @type {Node<float>}
  9098. */
  9099. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9100. /**
  9101. * TSL object that represents the sheen color of the current material.
  9102. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9103. *
  9104. * @type {Node<vec3>}
  9105. */
  9106. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9107. /**
  9108. * TSL object that represents the sheen roughness of the current material.
  9109. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9110. *
  9111. * @type {Node<float>}
  9112. */
  9113. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9114. /**
  9115. * TSL object that represents the anisotropy of the current material.
  9116. *
  9117. * @type {Node<vec2>}
  9118. */
  9119. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9120. /**
  9121. * TSL object that represents the iridescence of the current material.
  9122. *
  9123. * @type {Node<float>}
  9124. */
  9125. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9126. /**
  9127. * TSL object that represents the iridescence IOR of the current material.
  9128. *
  9129. * @type {Node<float>}
  9130. */
  9131. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9132. /**
  9133. * TSL object that represents the iridescence thickness of the current material.
  9134. *
  9135. * @type {Node<float>}
  9136. */
  9137. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9138. /**
  9139. * TSL object that represents the transmission of the current material.
  9140. * The value is composed via `transmission` * `transmissionMap.r`.
  9141. *
  9142. * @type {Node<float>}
  9143. */
  9144. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9145. /**
  9146. * TSL object that represents the thickness of the current material.
  9147. * The value is composed via `thickness` * `thicknessMap.g`.
  9148. *
  9149. * @type {Node<float>}
  9150. */
  9151. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9152. /**
  9153. * TSL object that represents the IOR of the current material.
  9154. *
  9155. * @type {Node<float>}
  9156. */
  9157. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  9158. /**
  9159. * TSL object that represents the attenuation distance of the current material.
  9160. *
  9161. * @type {Node<float>}
  9162. */
  9163. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  9164. /**
  9165. * TSL object that represents the attenuation color of the current material.
  9166. *
  9167. * @type {Node<vec3>}
  9168. */
  9169. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  9170. /**
  9171. * TSL object that represents the scale of the current dashed line material.
  9172. *
  9173. * @type {Node<float>}
  9174. */
  9175. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  9176. /**
  9177. * TSL object that represents the dash size of the current dashed line material.
  9178. *
  9179. * @type {Node<float>}
  9180. */
  9181. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  9182. /**
  9183. * TSL object that represents the gap size of the current dashed line material.
  9184. *
  9185. * @type {Node<float>}
  9186. */
  9187. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  9188. /**
  9189. * TSL object that represents the line width of the current line material.
  9190. *
  9191. * @type {Node<float>}
  9192. */
  9193. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  9194. /**
  9195. * TSL object that represents the dash offset of the current line material.
  9196. *
  9197. * @type {Node<float>}
  9198. */
  9199. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  9200. /**
  9201. * TSL object that represents the point size of the current points material.
  9202. *
  9203. * @type {Node<float>}
  9204. */
  9205. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9206. /**
  9207. * TSL object that represents the dispersion of the current material.
  9208. *
  9209. * @type {Node<float>}
  9210. */
  9211. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9212. /**
  9213. * TSL object that represents the light map of the current material.
  9214. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9215. *
  9216. * @type {Node<vec3>}
  9217. */
  9218. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9219. /**
  9220. * TSL object that represents the ambient occlusion map of the current material.
  9221. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9222. *
  9223. * @type {Node<float>}
  9224. */
  9225. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9226. /**
  9227. * TSL object that represents the anisotropy vector of the current material.
  9228. *
  9229. * @type {Node<vec2>}
  9230. */
  9231. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9232. return frame.material;
  9233. } ).onRenderUpdate( function ( { material } ) {
  9234. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9235. } );
  9236. /** @module ModelViewProjectionNode **/
  9237. /**
  9238. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9239. *
  9240. * @type {VaryingNode<vec4>}
  9241. */
  9242. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9243. return builder.context.setupModelViewProjection();
  9244. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  9245. /** @module IndexNode **/
  9246. /**
  9247. * This class represents shader indices of different types. The following predefined node
  9248. * objects cover frequent use cases:
  9249. *
  9250. * - `vertexIndex`: The index of a vertex within a mesh.
  9251. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9252. * - `drawIndex`: The index of a draw call.
  9253. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9254. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9255. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9256. *
  9257. * @augments Node
  9258. */
  9259. class IndexNode extends Node {
  9260. static get type() {
  9261. return 'IndexNode';
  9262. }
  9263. /**
  9264. * Constructs a new index node.
  9265. *
  9266. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9267. */
  9268. constructor( scope ) {
  9269. super( 'uint' );
  9270. /**
  9271. * The scope of the index node.
  9272. *
  9273. * @type {String}
  9274. */
  9275. this.scope = scope;
  9276. /**
  9277. * This flag can be used for type testing.
  9278. *
  9279. * @type {Boolean}
  9280. * @readonly
  9281. * @default true
  9282. */
  9283. this.isIndexNode = true;
  9284. }
  9285. generate( builder ) {
  9286. const nodeType = this.getNodeType( builder );
  9287. const scope = this.scope;
  9288. let propertyName;
  9289. if ( scope === IndexNode.VERTEX ) {
  9290. propertyName = builder.getVertexIndex();
  9291. } else if ( scope === IndexNode.INSTANCE ) {
  9292. propertyName = builder.getInstanceIndex();
  9293. } else if ( scope === IndexNode.DRAW ) {
  9294. propertyName = builder.getDrawIndex();
  9295. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9296. propertyName = builder.getInvocationLocalIndex();
  9297. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9298. propertyName = builder.getInvocationSubgroupIndex();
  9299. } else if ( scope === IndexNode.SUBGROUP ) {
  9300. propertyName = builder.getSubgroupIndex();
  9301. } else {
  9302. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9303. }
  9304. let output;
  9305. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9306. output = propertyName;
  9307. } else {
  9308. const nodeVarying = varying( this );
  9309. output = nodeVarying.build( builder, nodeType );
  9310. }
  9311. return output;
  9312. }
  9313. }
  9314. IndexNode.VERTEX = 'vertex';
  9315. IndexNode.INSTANCE = 'instance';
  9316. IndexNode.SUBGROUP = 'subgroup';
  9317. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9318. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9319. IndexNode.DRAW = 'draw';
  9320. /**
  9321. * TSL object that represents the index of a vertex within a mesh.
  9322. *
  9323. * @type {IndexNode}
  9324. */
  9325. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9326. /**
  9327. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9328. *
  9329. * @type {IndexNode}
  9330. */
  9331. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9332. /**
  9333. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9334. *
  9335. * @type {IndexNode}
  9336. */
  9337. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9338. /**
  9339. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9340. *
  9341. * @type {IndexNode}
  9342. */
  9343. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9344. /**
  9345. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9346. *
  9347. * @type {IndexNode}
  9348. */
  9349. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9350. /**
  9351. * TSL object that represents the index of a draw call.
  9352. *
  9353. * @type {IndexNode}
  9354. */
  9355. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9356. /** @module InstanceNode **/
  9357. /**
  9358. * This node implements the vertex shader logic which is required
  9359. * when rendering 3D objects via instancing. The code makes sure
  9360. * vertex positions, normals and colors can be modified via instanced
  9361. * data.
  9362. *
  9363. * @augments Node
  9364. */
  9365. class InstanceNode extends Node {
  9366. static get type() {
  9367. return 'InstanceNode';
  9368. }
  9369. /**
  9370. * Constructs a new instance node.
  9371. *
  9372. * @param {Number} count - The number of instances.
  9373. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9374. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9375. */
  9376. constructor( count, instanceMatrix, instanceColor ) {
  9377. super( 'void' );
  9378. /**
  9379. * The number of instances.
  9380. *
  9381. * @type {Number}
  9382. */
  9383. this.count = count;
  9384. /**
  9385. * Instanced buffer attribute representing the transformation of instances.
  9386. *
  9387. * @type {InstancedBufferAttribute}
  9388. */
  9389. this.instanceMatrix = instanceMatrix;
  9390. /**
  9391. * Instanced buffer attribute representing the color of instances.
  9392. *
  9393. * @type {InstancedBufferAttribute}
  9394. */
  9395. this.instanceColor = instanceColor;
  9396. /**
  9397. * The node that represents the instance matrix data.
  9398. *
  9399. * @type {Node}
  9400. */
  9401. this.instanceMatrixNode = null;
  9402. /**
  9403. * The node that represents the instance color data.
  9404. *
  9405. * @type {Node}
  9406. */
  9407. this.instanceColorNode = null;
  9408. /**
  9409. * The update type is set to `frame` since an update
  9410. * of instanced buffer data must be checked per frame.
  9411. *
  9412. * @type {String}
  9413. * @default 'frame'
  9414. */
  9415. this.updateType = NodeUpdateType.FRAME;
  9416. /**
  9417. * A reference to a buffer that is used by `instanceMatrixNode`.
  9418. *
  9419. * @type {InstancedInterleavedBuffer}
  9420. */
  9421. this.buffer = null;
  9422. /**
  9423. * A reference to a buffer that is used by `instanceColorNode`.
  9424. *
  9425. * @type {InstancedBufferAttribute}
  9426. */
  9427. this.bufferColor = null;
  9428. }
  9429. /**
  9430. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9431. * to predefined node variables for accumulation. That follows the same patterns
  9432. * like with morph and skinning nodes.
  9433. *
  9434. * @param {NodeBuilder} builder - The current node builder.
  9435. */
  9436. setup( builder ) {
  9437. const { count, instanceMatrix, instanceColor } = this;
  9438. let { instanceMatrixNode, instanceColorNode } = this;
  9439. if ( instanceMatrixNode === null ) {
  9440. // 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.
  9441. if ( count <= 1000 ) {
  9442. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9443. } else {
  9444. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9445. this.buffer = buffer;
  9446. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9447. const instanceBuffers = [
  9448. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9449. bufferFn( buffer, 'vec4', 16, 0 ),
  9450. bufferFn( buffer, 'vec4', 16, 4 ),
  9451. bufferFn( buffer, 'vec4', 16, 8 ),
  9452. bufferFn( buffer, 'vec4', 16, 12 )
  9453. ];
  9454. instanceMatrixNode = mat4( ...instanceBuffers );
  9455. }
  9456. this.instanceMatrixNode = instanceMatrixNode;
  9457. }
  9458. if ( instanceColor && instanceColorNode === null ) {
  9459. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9460. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9461. this.bufferColor = buffer;
  9462. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9463. this.instanceColorNode = instanceColorNode;
  9464. }
  9465. // POSITION
  9466. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9467. positionLocal.assign( instancePosition );
  9468. // NORMAL
  9469. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9470. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9471. // ASSIGNS
  9472. normalLocal.assign( instanceNormal );
  9473. }
  9474. // COLOR
  9475. if ( this.instanceColorNode !== null ) {
  9476. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9477. }
  9478. }
  9479. /**
  9480. * Checks if the internal buffers required an update.
  9481. *
  9482. * @param {NodeFrame} frame - The current node frame.
  9483. */
  9484. update( /*frame*/ ) {
  9485. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9486. this.buffer.version = this.instanceMatrix.version;
  9487. }
  9488. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9489. this.bufferColor.version = this.instanceColor.version;
  9490. }
  9491. }
  9492. }
  9493. /**
  9494. * TSL function for creating an instance node.
  9495. *
  9496. * @function
  9497. * @param {Number} count - The number of instances.
  9498. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9499. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9500. * @returns {InstanceNode}
  9501. */
  9502. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9503. /** @module InstancedMeshNode **/
  9504. /**
  9505. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9506. * It allows an easier setup of the instance node.
  9507. *
  9508. * @augments module:InstanceNode~InstanceNode
  9509. */
  9510. class InstancedMeshNode extends InstanceNode {
  9511. static get type() {
  9512. return 'InstancedMeshNode';
  9513. }
  9514. /**
  9515. * Constructs a new instanced mesh node.
  9516. *
  9517. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9518. */
  9519. constructor( instancedMesh ) {
  9520. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9521. super( count, instanceMatrix, instanceColor );
  9522. /**
  9523. * A reference to the instanced mesh.
  9524. *
  9525. * @type {InstancedMesh}
  9526. */
  9527. this.instancedMesh = instancedMesh;
  9528. }
  9529. }
  9530. /**
  9531. * TSL function for creating an instanced mesh node.
  9532. *
  9533. * @function
  9534. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9535. * @returns {InstancedMeshNode}
  9536. */
  9537. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9538. /** @module BatchNode **/
  9539. /**
  9540. * This node implements the vertex shader logic which is required
  9541. * when rendering 3D objects via batching. `BatchNode` must be used
  9542. * with instances of {@link BatchedMesh}.
  9543. *
  9544. * @augments Node
  9545. */
  9546. class BatchNode extends Node {
  9547. static get type() {
  9548. return 'BatchNode';
  9549. }
  9550. /**
  9551. * Constructs a new batch node.
  9552. *
  9553. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9554. */
  9555. constructor( batchMesh ) {
  9556. super( 'void' );
  9557. /**
  9558. * A reference to batched mesh.
  9559. *
  9560. * @type {BatchedMesh}
  9561. */
  9562. this.batchMesh = batchMesh;
  9563. /**
  9564. * The batching index node.
  9565. *
  9566. * @type {IndexNode?}
  9567. * @default null
  9568. */
  9569. this.batchingIdNode = null;
  9570. }
  9571. /**
  9572. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9573. * to predefined node variables for accumulation. That follows the same patterns
  9574. * like with morph and skinning nodes.
  9575. *
  9576. * @param {NodeBuilder} builder - The current node builder.
  9577. */
  9578. setup( builder ) {
  9579. if ( this.batchingIdNode === null ) {
  9580. if ( builder.getDrawIndex() === null ) {
  9581. this.batchingIdNode = instanceIndex;
  9582. } else {
  9583. this.batchingIdNode = drawIndex;
  9584. }
  9585. }
  9586. const getIndirectIndex = Fn( ( [ id ] ) => {
  9587. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ) );
  9588. const x = int( id ).modInt( size );
  9589. const y = int( id ).div( size );
  9590. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9591. } ).setLayout( {
  9592. name: 'getIndirectIndex',
  9593. type: 'uint',
  9594. inputs: [
  9595. { name: 'id', type: 'int' }
  9596. ]
  9597. } );
  9598. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9599. const matricesTexture = this.batchMesh._matricesTexture;
  9600. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9601. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9602. const x = j.modInt( size );
  9603. const y = j.div( int( size ) );
  9604. const batchingMatrix = mat4(
  9605. textureLoad( matricesTexture, ivec2( x, y ) ),
  9606. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9607. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9608. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9609. );
  9610. const colorsTexture = this.batchMesh._colorsTexture;
  9611. if ( colorsTexture !== null ) {
  9612. const getBatchingColor = Fn( ( [ id ] ) => {
  9613. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9614. const j = id;
  9615. const x = j.modInt( size );
  9616. const y = j.div( size );
  9617. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9618. } ).setLayout( {
  9619. name: 'getBatchingColor',
  9620. type: 'vec3',
  9621. inputs: [
  9622. { name: 'id', type: 'int' }
  9623. ]
  9624. } );
  9625. const color = getBatchingColor( indirectId );
  9626. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9627. }
  9628. const bm = mat3( batchingMatrix );
  9629. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9630. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9631. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9632. normalLocal.assign( batchingNormal );
  9633. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9634. tangentLocal.mulAssign( bm );
  9635. }
  9636. }
  9637. }
  9638. /**
  9639. * TSL function for creating a batch node.
  9640. *
  9641. * @function
  9642. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9643. * @returns {BatchNode}
  9644. */
  9645. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9646. /** @module SkinningNode **/
  9647. const _frameId = new WeakMap();
  9648. /**
  9649. * This node implements the vertex transformation shader logic which is required
  9650. * for skinning/skeletal animation.
  9651. *
  9652. * @augments Node
  9653. */
  9654. class SkinningNode extends Node {
  9655. static get type() {
  9656. return 'SkinningNode';
  9657. }
  9658. /**
  9659. * Constructs a new skinning node.
  9660. *
  9661. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9662. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9663. */
  9664. constructor( skinnedMesh, useReference = false ) {
  9665. super( 'void' );
  9666. /**
  9667. * The skinned mesh.
  9668. *
  9669. * @type {SkinnedMesh}
  9670. */
  9671. this.skinnedMesh = skinnedMesh;
  9672. /**
  9673. * Whether to use reference nodes for internal skinned mesh related data or not.
  9674. * TODO: Explain the purpose of the property.
  9675. *
  9676. * @type {Boolean}
  9677. */
  9678. this.useReference = useReference;
  9679. /**
  9680. * The update type overwritten since skinning nodes are updated per object.
  9681. *
  9682. * @type {String}
  9683. */
  9684. this.updateType = NodeUpdateType.OBJECT;
  9685. //
  9686. /**
  9687. * The skin index attribute.
  9688. *
  9689. * @type {AttributeNode}
  9690. */
  9691. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9692. /**
  9693. * The skin weight attribute.
  9694. *
  9695. * @type {AttributeNode}
  9696. */
  9697. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9698. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9699. if ( useReference ) {
  9700. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9701. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9702. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9703. } else {
  9704. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9705. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9706. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9707. }
  9708. /**
  9709. * The bind matrix node.
  9710. *
  9711. * @type {Node<mat4>}
  9712. */
  9713. this.bindMatrixNode = bindMatrixNode;
  9714. /**
  9715. * The bind matrix inverse node.
  9716. *
  9717. * @type {Node<mat4>}
  9718. */
  9719. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9720. /**
  9721. * The bind matrices as a uniform buffer node.
  9722. *
  9723. * @type {Node}
  9724. */
  9725. this.boneMatricesNode = boneMatricesNode;
  9726. /**
  9727. * The previous bind matrices as a uniform buffer node.
  9728. * Required for computing motion vectors.
  9729. *
  9730. * @type {Node?}
  9731. * @default null
  9732. */
  9733. this.previousBoneMatricesNode = null;
  9734. }
  9735. /**
  9736. * Transforms the given vertex position via skinning.
  9737. *
  9738. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9739. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9740. * @return {Node<vec3>} The transformed vertex position.
  9741. */
  9742. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9743. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9744. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9745. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9746. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9747. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9748. // POSITION
  9749. const skinVertex = bindMatrixNode.mul( position );
  9750. const skinned = add(
  9751. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9752. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9753. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9754. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9755. );
  9756. return bindMatrixInverseNode.mul( skinned ).xyz;
  9757. }
  9758. /**
  9759. * Transforms the given vertex normal via skinning.
  9760. *
  9761. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9762. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9763. * @return {Node<vec3>} The transformed vertex normal.
  9764. */
  9765. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9766. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9767. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9768. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9769. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9770. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9771. // NORMAL
  9772. let skinMatrix = add(
  9773. skinWeightNode.x.mul( boneMatX ),
  9774. skinWeightNode.y.mul( boneMatY ),
  9775. skinWeightNode.z.mul( boneMatZ ),
  9776. skinWeightNode.w.mul( boneMatW )
  9777. );
  9778. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9779. return skinMatrix.transformDirection( normal ).xyz;
  9780. }
  9781. /**
  9782. * Transforms the given vertex normal via skinning.
  9783. *
  9784. * @param {NodeBuilder} builder - The current node builder.
  9785. * @return {Node<vec3>} The skinned position from the previous frame.
  9786. */
  9787. getPreviousSkinnedPosition( builder ) {
  9788. const skinnedMesh = builder.object;
  9789. if ( this.previousBoneMatricesNode === null ) {
  9790. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9791. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9792. }
  9793. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9794. }
  9795. /**
  9796. * Returns `true` if bone matrices from the previous frame are required.
  9797. *
  9798. * @param {NodeBuilder} builder - The current node builder.
  9799. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9800. */
  9801. needsPreviousBoneMatrices( builder ) {
  9802. const mrt = builder.renderer.getMRT();
  9803. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9804. }
  9805. /**
  9806. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9807. *
  9808. * @param {NodeBuilder} builder - The current node builder.
  9809. */
  9810. setup( builder ) {
  9811. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9812. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9813. }
  9814. const skinPosition = this.getSkinnedPosition();
  9815. positionLocal.assign( skinPosition );
  9816. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9817. const skinNormal = this.getSkinnedNormal();
  9818. normalLocal.assign( skinNormal );
  9819. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9820. tangentLocal.assign( skinNormal );
  9821. }
  9822. }
  9823. }
  9824. /**
  9825. * Generates the code snippet of the skinning node.
  9826. *
  9827. * @param {NodeBuilder} builder - The current node builder.
  9828. * @param {String} output - The current output.
  9829. * @return {String} The generated code snippet.
  9830. */
  9831. generate( builder, output ) {
  9832. if ( output !== 'void' ) {
  9833. return positionLocal.build( builder, output );
  9834. }
  9835. }
  9836. /**
  9837. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9838. *
  9839. * @param {NodeFrame} frame - The current node frame.
  9840. */
  9841. update( frame ) {
  9842. const object = this.useReference ? frame.object : this.skinnedMesh;
  9843. const skeleton = object.skeleton;
  9844. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9845. _frameId.set( skeleton, frame.frameId );
  9846. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9847. skeleton.update();
  9848. }
  9849. }
  9850. /**
  9851. * TSL function for creating a skinning node.
  9852. *
  9853. * @function
  9854. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9855. * @returns {SkinningNode}
  9856. */
  9857. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9858. /**
  9859. * TSL function for creating a skinning node with reference usage.
  9860. *
  9861. * @function
  9862. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9863. * @returns {SkinningNode}
  9864. */
  9865. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9866. /** @module LoopNode **/
  9867. /**
  9868. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9869. * ```js
  9870. * Loop( count, ( { i } ) => {
  9871. *
  9872. * } );
  9873. * ```
  9874. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9875. * ```js
  9876. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9877. *
  9878. * } );
  9879. *```
  9880. * Nested loops can be defined in a compacted form:
  9881. * ```js
  9882. * Loop( 10, 5, ( { i, j } ) => {
  9883. *
  9884. * } );
  9885. * ```
  9886. * Loops that should run backwards can be defined like so:
  9887. * ```js
  9888. * Loop( { start: 10 }, () => {} );
  9889. * ```
  9890. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9891. * @augments Node
  9892. */
  9893. class LoopNode extends Node {
  9894. static get type() {
  9895. return 'LoopNode';
  9896. }
  9897. /**
  9898. * Constructs a new loop node.
  9899. *
  9900. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9901. */
  9902. constructor( params = [] ) {
  9903. super();
  9904. this.params = params;
  9905. }
  9906. /**
  9907. * Returns a loop variable name based on an index. The pattern is
  9908. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9909. *
  9910. * @param {Number} index - The index.
  9911. * @return {String} The loop variable name.
  9912. */
  9913. getVarName( index ) {
  9914. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9915. }
  9916. /**
  9917. * Returns properties about this node.
  9918. *
  9919. * @param {NodeBuilder} builder - The current node builder.
  9920. * @return {Object} The node properties.
  9921. */
  9922. getProperties( builder ) {
  9923. const properties = builder.getNodeProperties( this );
  9924. if ( properties.stackNode !== undefined ) return properties;
  9925. //
  9926. const inputs = {};
  9927. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9928. const param = this.params[ i ];
  9929. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9930. const type = ( param.isNode !== true && param.type ) || 'int';
  9931. inputs[ name ] = expression( name, type );
  9932. }
  9933. const stack = builder.addStack(); // TODO: cache() it
  9934. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9935. properties.stackNode = stack;
  9936. builder.removeStack();
  9937. return properties;
  9938. }
  9939. /**
  9940. * This method is overwritten since the node type is inferred based on the loop configuration.
  9941. *
  9942. * @param {NodeBuilder} builder - The current node builder.
  9943. * @return {String} The node type.
  9944. */
  9945. getNodeType( builder ) {
  9946. const { returnsNode } = this.getProperties( builder );
  9947. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9948. }
  9949. setup( builder ) {
  9950. // setup properties
  9951. this.getProperties( builder );
  9952. }
  9953. generate( builder ) {
  9954. const properties = this.getProperties( builder );
  9955. const params = this.params;
  9956. const stackNode = properties.stackNode;
  9957. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9958. const param = params[ i ];
  9959. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9960. if ( param.isNode ) {
  9961. type = 'int';
  9962. name = this.getVarName( i );
  9963. start = '0';
  9964. end = param.build( builder, type );
  9965. condition = '<';
  9966. } else {
  9967. type = param.type || 'int';
  9968. name = param.name || this.getVarName( i );
  9969. start = param.start;
  9970. end = param.end;
  9971. condition = param.condition;
  9972. update = param.update;
  9973. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9974. else if ( start && start.isNode ) start = start.build( builder, type );
  9975. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9976. else if ( end && end.isNode ) end = end.build( builder, type );
  9977. if ( start !== undefined && end === undefined ) {
  9978. start = start + ' - 1';
  9979. end = '0';
  9980. condition = '>=';
  9981. } else if ( end !== undefined && start === undefined ) {
  9982. start = '0';
  9983. condition = '<';
  9984. }
  9985. if ( condition === undefined ) {
  9986. if ( Number( start ) > Number( end ) ) {
  9987. condition = '>=';
  9988. } else {
  9989. condition = '<';
  9990. }
  9991. }
  9992. }
  9993. const internalParam = { start, end, condition };
  9994. //
  9995. const startSnippet = internalParam.start;
  9996. const endSnippet = internalParam.end;
  9997. let declarationSnippet = '';
  9998. let conditionalSnippet = '';
  9999. let updateSnippet = '';
  10000. if ( ! update ) {
  10001. if ( type === 'int' || type === 'uint' ) {
  10002. if ( condition.includes( '<' ) ) update = '++';
  10003. else update = '--';
  10004. } else {
  10005. if ( condition.includes( '<' ) ) update = '+= 1.';
  10006. else update = '-= 1.';
  10007. }
  10008. }
  10009. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  10010. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  10011. updateSnippet += name + ' ' + update;
  10012. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  10013. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  10014. }
  10015. const stackSnippet = stackNode.build( builder, 'void' );
  10016. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  10017. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  10018. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  10019. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  10020. }
  10021. builder.addFlowTab();
  10022. return returnsSnippet;
  10023. }
  10024. }
  10025. /**
  10026. * TSL function for creating a loop node.
  10027. *
  10028. * @function
  10029. * @param {...Any} params - A list of parameters.
  10030. * @returns {LoopNode}
  10031. */
  10032. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  10033. /**
  10034. * TSL function for creating a `Continue()` expression.
  10035. *
  10036. * @function
  10037. * @returns {ExpressionNode}
  10038. */
  10039. const Continue = () => expression( 'continue' ).append();
  10040. /**
  10041. * TSL function for creating a `Break()` expression.
  10042. *
  10043. * @function
  10044. * @returns {ExpressionNode}
  10045. */
  10046. const Break = () => expression( 'break' ).append();
  10047. // Deprecated
  10048. /**
  10049. * @function
  10050. * @deprecated since r168. Use {@link Loop} instead.
  10051. *
  10052. * @param {...any} params
  10053. * @returns {LoopNode}
  10054. */
  10055. const loop = ( ...params ) => { // @deprecated, r168
  10056. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  10057. return Loop( ...params );
  10058. };
  10059. /** @module MorphNode **/
  10060. const _morphTextures = /*@__PURE__*/ new WeakMap();
  10061. const _morphVec4 = /*@__PURE__*/ new Vector4();
  10062. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  10063. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  10064. const y = texelIndex.div( width );
  10065. const x = texelIndex.sub( y.mul( width ) );
  10066. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  10067. return bufferAttrib.mul( influence );
  10068. } );
  10069. function getEntry( geometry ) {
  10070. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10071. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10072. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10073. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10074. // into an array of data textures. Each layer represents a single morph target.
  10075. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10076. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10077. let entry = _morphTextures.get( geometry );
  10078. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10079. if ( entry !== undefined ) entry.texture.dispose();
  10080. const morphTargets = geometry.morphAttributes.position || [];
  10081. const morphNormals = geometry.morphAttributes.normal || [];
  10082. const morphColors = geometry.morphAttributes.color || [];
  10083. let vertexDataCount = 0;
  10084. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10085. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10086. if ( hasMorphColors === true ) vertexDataCount = 3;
  10087. let width = geometry.attributes.position.count * vertexDataCount;
  10088. let height = 1;
  10089. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  10090. if ( width > maxTextureSize ) {
  10091. height = Math.ceil( width / maxTextureSize );
  10092. width = maxTextureSize;
  10093. }
  10094. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10095. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10096. bufferTexture.type = FloatType;
  10097. bufferTexture.needsUpdate = true;
  10098. // fill buffer
  10099. const vertexDataStride = vertexDataCount * 4;
  10100. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10101. const morphTarget = morphTargets[ i ];
  10102. const morphNormal = morphNormals[ i ];
  10103. const morphColor = morphColors[ i ];
  10104. const offset = width * height * 4 * i;
  10105. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10106. const stride = j * vertexDataStride;
  10107. if ( hasMorphPosition === true ) {
  10108. _morphVec4.fromBufferAttribute( morphTarget, j );
  10109. buffer[ offset + stride + 0 ] = _morphVec4.x;
  10110. buffer[ offset + stride + 1 ] = _morphVec4.y;
  10111. buffer[ offset + stride + 2 ] = _morphVec4.z;
  10112. buffer[ offset + stride + 3 ] = 0;
  10113. }
  10114. if ( hasMorphNormals === true ) {
  10115. _morphVec4.fromBufferAttribute( morphNormal, j );
  10116. buffer[ offset + stride + 4 ] = _morphVec4.x;
  10117. buffer[ offset + stride + 5 ] = _morphVec4.y;
  10118. buffer[ offset + stride + 6 ] = _morphVec4.z;
  10119. buffer[ offset + stride + 7 ] = 0;
  10120. }
  10121. if ( hasMorphColors === true ) {
  10122. _morphVec4.fromBufferAttribute( morphColor, j );
  10123. buffer[ offset + stride + 8 ] = _morphVec4.x;
  10124. buffer[ offset + stride + 9 ] = _morphVec4.y;
  10125. buffer[ offset + stride + 10 ] = _morphVec4.z;
  10126. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  10127. }
  10128. }
  10129. }
  10130. entry = {
  10131. count: morphTargetsCount,
  10132. texture: bufferTexture,
  10133. stride: vertexDataCount,
  10134. size: new Vector2( width, height )
  10135. };
  10136. _morphTextures.set( geometry, entry );
  10137. function disposeTexture() {
  10138. bufferTexture.dispose();
  10139. _morphTextures.delete( geometry );
  10140. geometry.removeEventListener( 'dispose', disposeTexture );
  10141. }
  10142. geometry.addEventListener( 'dispose', disposeTexture );
  10143. }
  10144. return entry;
  10145. }
  10146. /**
  10147. * This node implements the vertex transformation shader logic which is required
  10148. * for morph target animation.
  10149. *
  10150. * @augments Node
  10151. */
  10152. class MorphNode extends Node {
  10153. static get type() {
  10154. return 'MorphNode';
  10155. }
  10156. /**
  10157. * Constructs a new morph node.
  10158. *
  10159. * @param {Mesh} mesh - The mesh holding the morph targets.
  10160. */
  10161. constructor( mesh ) {
  10162. super( 'void' );
  10163. /**
  10164. * The mesh holding the morph targets.
  10165. *
  10166. * @type {Mesh}
  10167. */
  10168. this.mesh = mesh;
  10169. /**
  10170. * A uniform node which represents the morph base influence value.
  10171. *
  10172. * @type {UniformNode<float>}
  10173. */
  10174. this.morphBaseInfluence = uniform( 1 );
  10175. /**
  10176. * The update type overwritten since morph nodes are updated per object.
  10177. *
  10178. * @type {String}
  10179. */
  10180. this.updateType = NodeUpdateType.OBJECT;
  10181. }
  10182. /**
  10183. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  10184. *
  10185. * @param {NodeBuilder} builder - The current node builder.
  10186. */
  10187. setup( builder ) {
  10188. const { geometry } = builder;
  10189. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10190. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  10191. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10192. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10193. // nodes
  10194. const { texture: bufferMap, stride, size } = getEntry( geometry );
  10195. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  10196. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  10197. const width = int( size.width );
  10198. Loop( morphTargetsCount, ( { i } ) => {
  10199. const influence = float( 0 ).toVar();
  10200. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  10201. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  10202. } else {
  10203. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  10204. }
  10205. if ( hasMorphPosition === true ) {
  10206. positionLocal.addAssign( getMorph( {
  10207. bufferMap,
  10208. influence,
  10209. stride,
  10210. width,
  10211. depth: i,
  10212. offset: int( 0 )
  10213. } ) );
  10214. }
  10215. if ( hasMorphNormals === true ) {
  10216. normalLocal.addAssign( getMorph( {
  10217. bufferMap,
  10218. influence,
  10219. stride,
  10220. width,
  10221. depth: i,
  10222. offset: int( 1 )
  10223. } ) );
  10224. }
  10225. } );
  10226. }
  10227. /**
  10228. * Updates the state of the morphed mesh by updating the base influence.
  10229. *
  10230. * @param {NodeFrame} frame - The current node frame.
  10231. */
  10232. update( /*frame*/ ) {
  10233. const morphBaseInfluence = this.morphBaseInfluence;
  10234. if ( this.mesh.geometry.morphTargetsRelative ) {
  10235. morphBaseInfluence.value = 1;
  10236. } else {
  10237. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10238. }
  10239. }
  10240. }
  10241. /**
  10242. * TSL function for creating a morph node.
  10243. *
  10244. * @function
  10245. * @param {Mesh} mesh - The mesh holding the morph targets.
  10246. * @returns {MorphNode}
  10247. */
  10248. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10249. /**
  10250. * Base class for lighting nodes.
  10251. *
  10252. * @augments Node
  10253. */
  10254. class LightingNode extends Node {
  10255. static get type() {
  10256. return 'LightingNode';
  10257. }
  10258. /**
  10259. * Constructs a new lighting node.
  10260. */
  10261. constructor() {
  10262. super( 'vec3' );
  10263. /**
  10264. * This flag can be used for type testing.
  10265. *
  10266. * @type {Boolean}
  10267. * @readonly
  10268. * @default true
  10269. */
  10270. this.isLightingNode = true;
  10271. }
  10272. }
  10273. /**
  10274. * A generic class that can be used by nodes which contribute
  10275. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10276. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10277. *
  10278. * @augments LightingNode
  10279. */
  10280. class AONode extends LightingNode {
  10281. static get type() {
  10282. return 'AONode';
  10283. }
  10284. /**
  10285. * Constructs a new AO node.
  10286. *
  10287. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  10288. */
  10289. constructor( aoNode = null ) {
  10290. super();
  10291. /**
  10292. * The ambient occlusion node.
  10293. *
  10294. * @type {Node<float>?}
  10295. * @default null
  10296. */
  10297. this.aoNode = aoNode;
  10298. }
  10299. setup( builder ) {
  10300. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10301. }
  10302. }
  10303. /**
  10304. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  10305. * by adding lighting specific context data. It represents the runtime context of
  10306. * {@link LightsNode}.
  10307. *
  10308. * @augments ContextNode
  10309. */
  10310. class LightingContextNode extends ContextNode {
  10311. static get type() {
  10312. return 'LightingContextNode';
  10313. }
  10314. /**
  10315. * Constructs a new lighting context node.
  10316. *
  10317. * @param {LightsNode} node - The lights node.
  10318. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  10319. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  10320. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  10321. */
  10322. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10323. super( node );
  10324. /**
  10325. * The current lighting model.
  10326. *
  10327. * @type {LightingModel?}
  10328. * @default null
  10329. */
  10330. this.lightingModel = lightingModel;
  10331. /**
  10332. * A backdrop node.
  10333. *
  10334. * @type {Node<vec3>?}
  10335. * @default null
  10336. */
  10337. this.backdropNode = backdropNode;
  10338. /**
  10339. * A backdrop alpha node.
  10340. *
  10341. * @type {Node<float>?}
  10342. * @default null
  10343. */
  10344. this.backdropAlphaNode = backdropAlphaNode;
  10345. this._value = null;
  10346. }
  10347. /**
  10348. * Returns a lighting context object.
  10349. *
  10350. * @return {{
  10351. * radiance: Node<vec3>,
  10352. * irradiance: Node<vec3>,
  10353. * iblIrradiance: Node<vec3>,
  10354. * ambientOcclusion: Node<float>,
  10355. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10356. * backdrop: Node<vec3>,
  10357. * backdropAlpha: Node<float>
  10358. * }} The lighting context object.
  10359. */
  10360. getContext() {
  10361. const { backdropNode, backdropAlphaNode } = this;
  10362. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10363. directSpecular = vec3().toVar( 'directSpecular' ),
  10364. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10365. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10366. const reflectedLight = {
  10367. directDiffuse,
  10368. directSpecular,
  10369. indirectDiffuse,
  10370. indirectSpecular
  10371. };
  10372. const context = {
  10373. radiance: vec3().toVar( 'radiance' ),
  10374. irradiance: vec3().toVar( 'irradiance' ),
  10375. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10376. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10377. reflectedLight,
  10378. backdrop: backdropNode,
  10379. backdropAlpha: backdropAlphaNode
  10380. };
  10381. return context;
  10382. }
  10383. setup( builder ) {
  10384. this.value = this._value || ( this._value = this.getContext() );
  10385. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10386. return super.setup( builder );
  10387. }
  10388. }
  10389. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10390. /**
  10391. * A generic class that can be used by nodes which contribute
  10392. * irradiance to the scene. E.g. a light map node can be used
  10393. * as input for this module. Used in {@link NodeMaterial}.
  10394. *
  10395. * @augments LightingNode
  10396. */
  10397. class IrradianceNode extends LightingNode {
  10398. static get type() {
  10399. return 'IrradianceNode';
  10400. }
  10401. /**
  10402. * Constructs a new irradiance node.
  10403. *
  10404. * @param {Node<vec3>} node - A node contributing irradiance.
  10405. */
  10406. constructor( node ) {
  10407. super();
  10408. /**
  10409. * A node contributing irradiance.
  10410. *
  10411. * @type {Node<vec3>}
  10412. */
  10413. this.node = node;
  10414. }
  10415. setup( builder ) {
  10416. builder.context.irradiance.addAssign( this.node );
  10417. }
  10418. }
  10419. /** @module ScreenNode **/
  10420. let screenSizeVec, viewportVec;
  10421. /**
  10422. * This node provides a collection of screen related metrics.
  10423. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10424. * resolution or viewport data as well as fragment or uv coordinates.
  10425. *
  10426. * @augments Node
  10427. */
  10428. class ScreenNode extends Node {
  10429. static get type() {
  10430. return 'ScreenNode';
  10431. }
  10432. /**
  10433. * Constructs a new screen node.
  10434. *
  10435. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10436. */
  10437. constructor( scope ) {
  10438. super();
  10439. /**
  10440. * The node represents different metric depending on which scope is selected.
  10441. *
  10442. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10443. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10444. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10445. * - `ScreenNode.UV`: Normalized coordinates.
  10446. *
  10447. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10448. */
  10449. this.scope = scope;
  10450. /**
  10451. * This flag can be used for type testing.
  10452. *
  10453. * @type {Boolean}
  10454. * @readonly
  10455. * @default true
  10456. */
  10457. this.isViewportNode = true;
  10458. }
  10459. /**
  10460. * This method is overwritten since the node type depends on the selected scope.
  10461. *
  10462. * @return {('vec2'|'vec4')} The node type.
  10463. */
  10464. getNodeType() {
  10465. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10466. else return 'vec2';
  10467. }
  10468. /**
  10469. * This method is overwritten since the node's update type depends on the selected scope.
  10470. *
  10471. * @return {NodeUpdateType} The update type.
  10472. */
  10473. getUpdateType() {
  10474. let updateType = NodeUpdateType.NONE;
  10475. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10476. updateType = NodeUpdateType.RENDER;
  10477. }
  10478. this.updateType = updateType;
  10479. return updateType;
  10480. }
  10481. /**
  10482. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10483. * from the current renderer.
  10484. *
  10485. * @param {NodeFrame} frame - A reference to the current node frame.
  10486. */
  10487. update( { renderer } ) {
  10488. const renderTarget = renderer.getRenderTarget();
  10489. if ( this.scope === ScreenNode.VIEWPORT ) {
  10490. if ( renderTarget !== null ) {
  10491. viewportVec.copy( renderTarget.viewport );
  10492. } else {
  10493. renderer.getViewport( viewportVec );
  10494. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10495. }
  10496. } else {
  10497. if ( renderTarget !== null ) {
  10498. screenSizeVec.width = renderTarget.width;
  10499. screenSizeVec.height = renderTarget.height;
  10500. } else {
  10501. renderer.getDrawingBufferSize( screenSizeVec );
  10502. }
  10503. }
  10504. }
  10505. setup( /*builder*/ ) {
  10506. const scope = this.scope;
  10507. let output = null;
  10508. if ( scope === ScreenNode.SIZE ) {
  10509. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10510. } else if ( scope === ScreenNode.VIEWPORT ) {
  10511. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10512. } else {
  10513. output = vec2( screenCoordinate.div( screenSize ) );
  10514. }
  10515. return output;
  10516. }
  10517. generate( builder ) {
  10518. if ( this.scope === ScreenNode.COORDINATE ) {
  10519. let coord = builder.getFragCoord();
  10520. if ( builder.isFlipY() ) {
  10521. // follow webgpu standards
  10522. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10523. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10524. }
  10525. return coord;
  10526. }
  10527. return super.generate( builder );
  10528. }
  10529. }
  10530. ScreenNode.COORDINATE = 'coordinate';
  10531. ScreenNode.VIEWPORT = 'viewport';
  10532. ScreenNode.SIZE = 'size';
  10533. ScreenNode.UV = 'uv';
  10534. // Screen
  10535. /**
  10536. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10537. *
  10538. * @type {ScreenNode<vec2>}
  10539. */
  10540. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10541. /**
  10542. * TSL object that represents the screen resolution in physical pixel units.
  10543. *
  10544. * @type {ScreenNode<vec2>}
  10545. */
  10546. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10547. /**
  10548. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10549. *
  10550. * @type {ScreenNode<vec2>}
  10551. */
  10552. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10553. // Viewport
  10554. /**
  10555. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10556. *
  10557. * @type {ScreenNode<vec4>}
  10558. */
  10559. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10560. /**
  10561. * TSL object that represents the viewport resolution in physical pixel units.
  10562. *
  10563. * @type {ScreenNode<vec2>}
  10564. */
  10565. const viewportSize = viewport.zw;
  10566. /**
  10567. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10568. *
  10569. * @type {ScreenNode<vec2>}
  10570. */
  10571. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10572. /**
  10573. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10574. *
  10575. * @type {ScreenNode<vec2>}
  10576. */
  10577. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10578. // Deprecated
  10579. /**
  10580. * @deprecated since r169. Use {@link screenSize} instead.
  10581. */
  10582. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10583. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10584. return screenSize;
  10585. }, 'vec2' ).once() )();
  10586. /**
  10587. * @deprecated since r168. Use {@link screenUV} instead.
  10588. */
  10589. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10590. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10591. return screenUV;
  10592. }, 'vec2' ).once() )();
  10593. /**
  10594. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10595. */
  10596. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10597. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10598. return screenUV.flipY();
  10599. }, 'vec2' ).once() )();
  10600. /** @module ViewportTextureNode **/
  10601. const _size$4 = /*@__PURE__*/ new Vector2();
  10602. /**
  10603. * A special type of texture node which represents the data of the current viewport
  10604. * as a texture. The module extracts data from the current bound framebuffer with
  10605. * a copy operation so no extra render pass is required to produce the texture data
  10606. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10607. * variety of effects like refractive or transmissive materials.
  10608. *
  10609. * @augments module:TextureNode~TextureNode
  10610. */
  10611. class ViewportTextureNode extends TextureNode {
  10612. static get type() {
  10613. return 'ViewportTextureNode';
  10614. }
  10615. /**
  10616. * Constructs a new viewport texture node.
  10617. *
  10618. * @param {Node} [uvNode=screenUV] - The uv node.
  10619. * @param {Node?} [levelNode=null] - The level node.
  10620. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10621. */
  10622. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10623. if ( framebufferTexture === null ) {
  10624. framebufferTexture = new FramebufferTexture();
  10625. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10626. }
  10627. super( framebufferTexture, uvNode, levelNode );
  10628. /**
  10629. * Whether to generate mipmaps or not.
  10630. *
  10631. * @type {Boolean}
  10632. * @default false
  10633. */
  10634. this.generateMipmaps = false;
  10635. /**
  10636. * This flag can be used for type testing.
  10637. *
  10638. * @type {Boolean}
  10639. * @readonly
  10640. * @default true
  10641. */
  10642. this.isOutputTextureNode = true;
  10643. /**
  10644. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10645. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10646. *
  10647. * @type {String}
  10648. * @default 'frame'
  10649. */
  10650. this.updateBeforeType = NodeUpdateType.FRAME;
  10651. }
  10652. updateBefore( frame ) {
  10653. const renderer = frame.renderer;
  10654. renderer.getDrawingBufferSize( _size$4 );
  10655. //
  10656. const framebufferTexture = this.value;
  10657. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10658. framebufferTexture.image.width = _size$4.width;
  10659. framebufferTexture.image.height = _size$4.height;
  10660. framebufferTexture.needsUpdate = true;
  10661. }
  10662. //
  10663. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10664. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10665. renderer.copyFramebufferToTexture( framebufferTexture );
  10666. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10667. }
  10668. clone() {
  10669. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10670. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10671. return viewportTextureNode;
  10672. }
  10673. }
  10674. /**
  10675. * TSL function for creating a viewport texture node.
  10676. *
  10677. * @function
  10678. * @param {Node} [uvNode=screenUV] - The uv node.
  10679. * @param {Node?} [levelNode=null] - The level node.
  10680. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10681. * @returns {ViewportTextureNode}
  10682. */
  10683. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10684. /**
  10685. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10686. *
  10687. * @function
  10688. * @param {Node} [uvNode=screenUV] - The uv node.
  10689. * @param {Node?} [levelNode=null] - The level node.
  10690. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10691. * @returns {ViewportTextureNode}
  10692. */
  10693. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10694. /** @module ViewportDepthTextureNode **/
  10695. let sharedDepthbuffer = null;
  10696. /**
  10697. * Represents the depth of the current viewport as a texture. This module
  10698. * can be used in combination with viewport texture to achieve effects
  10699. * that require depth evaluation.
  10700. *
  10701. * @augments module:ViewportTextureNode~ViewportTextureNode
  10702. */
  10703. class ViewportDepthTextureNode extends ViewportTextureNode {
  10704. static get type() {
  10705. return 'ViewportDepthTextureNode';
  10706. }
  10707. /**
  10708. * Constructs a new viewport depth texture node.
  10709. *
  10710. * @param {Node} [uvNode=screenUV] - The uv node.
  10711. * @param {Node?} [levelNode=null] - The level node.
  10712. */
  10713. constructor( uvNode = screenUV, levelNode = null ) {
  10714. if ( sharedDepthbuffer === null ) {
  10715. sharedDepthbuffer = new DepthTexture();
  10716. }
  10717. super( uvNode, levelNode, sharedDepthbuffer );
  10718. }
  10719. }
  10720. /**
  10721. * TSL function for a viewport depth texture node.
  10722. *
  10723. * @function
  10724. * @param {Node} [uvNode=screenUV] - The uv node.
  10725. * @param {Node?} [levelNode=null] - The level node.
  10726. * @returns {ViewportDepthTextureNode}
  10727. */
  10728. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10729. /** @module ViewportDepthNode **/
  10730. /**
  10731. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10732. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10733. * fragment or for depth evaluation purposes.
  10734. *
  10735. * @augments Node
  10736. */
  10737. class ViewportDepthNode extends Node {
  10738. static get type() {
  10739. return 'ViewportDepthNode';
  10740. }
  10741. /**
  10742. * Constructs a new viewport depth node.
  10743. *
  10744. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10745. * @param {Node?} [valueNode=null] - The value node.
  10746. */
  10747. constructor( scope, valueNode = null ) {
  10748. super( 'float' );
  10749. /**
  10750. * The node behaves differently depending on which scope is selected.
  10751. *
  10752. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10753. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10754. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10755. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10756. *
  10757. * @type {('depth'|'depthBase'|'linearDepth')}
  10758. */
  10759. this.scope = scope;
  10760. /**
  10761. * Can be used to define a custom depth value.
  10762. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10763. *
  10764. * @type {Node?}
  10765. * @default null
  10766. */
  10767. this.valueNode = valueNode;
  10768. /**
  10769. * This flag can be used for type testing.
  10770. *
  10771. * @type {Boolean}
  10772. * @readonly
  10773. * @default true
  10774. */
  10775. this.isViewportDepthNode = true;
  10776. }
  10777. generate( builder ) {
  10778. const { scope } = this;
  10779. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10780. return builder.getFragDepth();
  10781. }
  10782. return super.generate( builder );
  10783. }
  10784. setup( { camera } ) {
  10785. const { scope } = this;
  10786. const value = this.valueNode;
  10787. let node = null;
  10788. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10789. if ( value !== null ) {
  10790. node = depthBase().assign( value );
  10791. }
  10792. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10793. if ( camera.isPerspectiveCamera ) {
  10794. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10795. } else {
  10796. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10797. }
  10798. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10799. if ( value !== null ) {
  10800. if ( camera.isPerspectiveCamera ) {
  10801. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10802. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10803. } else {
  10804. node = value;
  10805. }
  10806. } else {
  10807. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10808. }
  10809. }
  10810. return node;
  10811. }
  10812. }
  10813. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10814. ViewportDepthNode.DEPTH = 'depth';
  10815. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10816. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10817. /**
  10818. * TSL function for converting a viewZ value to an orthographic depth value.
  10819. *
  10820. * @function
  10821. * @param {Node<float>} viewZ - The viewZ node.
  10822. * @param {Node<float>} near - The camera's near value.
  10823. * @param {Node<float>} far - The camera's far value.
  10824. * @returns {Node<float>}
  10825. */
  10826. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10827. /**
  10828. * TSL function for converting an orthographic depth value to a viewZ value.
  10829. *
  10830. * @function
  10831. * @param {Node<float>} depth - The orthographic depth.
  10832. * @param {Node<float>} near - The camera's near value.
  10833. * @param {Node<float>} far - The camera's far value.
  10834. * @returns {Node<float>}
  10835. */
  10836. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10837. /**
  10838. * TSL function for converting a viewZ value to a perspective depth value.
  10839. *
  10840. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10841. *
  10842. * @function
  10843. * @param {Node<float>} viewZ - The viewZ node.
  10844. * @param {Node<float>} near - The camera's near value.
  10845. * @param {Node<float>} far - The camera's far value.
  10846. * @returns {Node<float>}
  10847. */
  10848. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10849. /**
  10850. * TSL function for converting a perspective depth value to a viewZ value.
  10851. *
  10852. * @function
  10853. * @param {Node<float>} depth - The perspective depth.
  10854. * @param {Node<float>} near - The camera's near value.
  10855. * @param {Node<float>} far - The camera's far value.
  10856. * @returns {Node<float>}
  10857. */
  10858. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10859. /**
  10860. * TSL function for converting a viewZ value to a logarithmic depth value.
  10861. *
  10862. * @function
  10863. * @param {Node<float>} viewZ - The viewZ node.
  10864. * @param {Node<float>} near - The camera's near value.
  10865. * @param {Node<float>} far - The camera's far value.
  10866. * @returns {Node<float>}
  10867. */
  10868. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10869. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10870. // The final logarithmic depth formula used here is adapted from one described in an
  10871. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10872. // which was an improvement upon an earlier formula one described in an
  10873. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10874. // Ulrich's formula is the following:
  10875. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10876. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10877. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10878. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10879. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10880. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10881. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10882. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10883. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10884. // Outerra eventually made another improvement to their original "C-constant" variant,
  10885. // but it still does not incorporate the camera near plane (for this version,
  10886. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10887. // Here we make 4 changes to Ulrich's formula:
  10888. // 1. Clamp the camera near plane so we don't divide by 0.
  10889. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10890. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10891. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10892. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10893. // so we do the same here, hence the 'viewZ.negate()' call.
  10894. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10895. near = near.max( 1e-6 ).toVar();
  10896. const numerator = log2( viewZ.negate().div( near ) );
  10897. const denominator = log2( far.div( near ) );
  10898. return numerator.div( denominator );
  10899. };
  10900. /**
  10901. * TSL function for converting a logarithmic depth value to a viewZ value.
  10902. *
  10903. * @function
  10904. * @param {Node<float>} depth - The logarithmic depth.
  10905. * @param {Node<float>} near - The camera's near value.
  10906. * @param {Node<float>} far - The camera's far value.
  10907. * @returns {Node<float>}
  10908. */
  10909. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10910. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10911. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10912. // a negative viewZ).
  10913. const exponent = depth.mul( log( far.div( near ) ) );
  10914. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10915. };
  10916. /**
  10917. * TSL function for defining a value for the current fragment's depth.
  10918. *
  10919. * @function
  10920. * @param {Node<float>} value - The depth value to set.
  10921. * @returns {ViewportDepthNode<float>}
  10922. */
  10923. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10924. /**
  10925. * TSL object that represents the depth value for the current fragment.
  10926. *
  10927. * @type {ViewportDepthNode}
  10928. */
  10929. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10930. /**
  10931. * TSL function for converting a perspective depth value to linear depth.
  10932. *
  10933. * @function
  10934. * @param {Node<float>} value - The perspective depth.
  10935. * @returns {ViewportDepthNode<float>}
  10936. */
  10937. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10938. /**
  10939. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10940. *
  10941. * @type {ViewportDepthNode}
  10942. */
  10943. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10944. depth.assign = ( value ) => depthBase( value );
  10945. /** @module BuiltinNode **/
  10946. /**
  10947. * The node allows to set values for built-in shader variables. That is
  10948. * required for features like hardware-accelerated vertex clipping.
  10949. *
  10950. * @augments Node
  10951. */
  10952. class BuiltinNode extends Node {
  10953. /**
  10954. * Constructs a new builtin node.
  10955. *
  10956. * @param {String} name - The name of the built-in shader variable.
  10957. */
  10958. constructor( name ) {
  10959. super( 'float' );
  10960. /**
  10961. * The name of the built-in shader variable.
  10962. *
  10963. * @type {String}
  10964. */
  10965. this.name = name;
  10966. /**
  10967. * This flag can be used for type testing.
  10968. *
  10969. * @type {Boolean}
  10970. * @readonly
  10971. * @default true
  10972. */
  10973. this.isBuiltinNode = true;
  10974. }
  10975. /**
  10976. * Generates the code snippet of the builtin node.
  10977. *
  10978. * @param {NodeBuilder} builder - The current node builder.
  10979. * @return {String} The generated code snippet.
  10980. */
  10981. generate( /* builder */ ) {
  10982. return this.name;
  10983. }
  10984. }
  10985. /**
  10986. * TSL function for creating a builtin node.
  10987. *
  10988. * @function
  10989. * @param {String} name - The name of the built-in shader variable.
  10990. * @returns {BuiltinNode}
  10991. */
  10992. const builtin = nodeProxy( BuiltinNode );
  10993. /** @module ClippingNode **/
  10994. /**
  10995. * ```
  10996. * This node is used in {@link NodeMaterial} to setup the clipping
  10997. * which can happen hardware-accelerated (if supported) and optionally
  10998. * use alpha-to-coverage for anti-aliasing clipped edges.
  10999. * ```
  11000. * @augments Node
  11001. */
  11002. class ClippingNode extends Node {
  11003. static get type() {
  11004. return 'ClippingNode';
  11005. }
  11006. /**
  11007. * Constructs a new clipping node.
  11008. *
  11009. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  11010. * the selected scope influences the behavior of the node and what type of code is generated.
  11011. */
  11012. constructor( scope = ClippingNode.DEFAULT ) {
  11013. super();
  11014. /**
  11015. * The node's scope. Similar to other nodes, the selected scope influences
  11016. * the behavior of the node and what type of code is generated.
  11017. *
  11018. * @type {('default'|'hardware'|'alphaToCoverage')}
  11019. */
  11020. this.scope = scope;
  11021. }
  11022. /**
  11023. * Setups the node depending on the selected scope.
  11024. *
  11025. * @param {NodeBuilder} builder - The current node builder.
  11026. * @return {Node} The result node.
  11027. */
  11028. setup( builder ) {
  11029. super.setup( builder );
  11030. const clippingContext = builder.clippingContext;
  11031. const { intersectionPlanes, unionPlanes } = clippingContext;
  11032. this.hardwareClipping = builder.material.hardwareClipping;
  11033. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  11034. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  11035. } else if ( this.scope === ClippingNode.HARDWARE ) {
  11036. return this.setupHardwareClipping( unionPlanes, builder );
  11037. } else {
  11038. return this.setupDefault( intersectionPlanes, unionPlanes );
  11039. }
  11040. }
  11041. /**
  11042. * Setups alpha to coverage.
  11043. *
  11044. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11045. * @param {Array<Vector4>} unionPlanes - The union planes.
  11046. * @return {Node} The result node.
  11047. */
  11048. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  11049. return Fn( () => {
  11050. const distanceToPlane = float().toVar( 'distanceToPlane' );
  11051. const distanceGradient = float().toVar( 'distanceToGradient' );
  11052. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  11053. const numUnionPlanes = unionPlanes.length;
  11054. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11055. const clippingPlanes = uniformArray( unionPlanes );
  11056. Loop( numUnionPlanes, ( { i } ) => {
  11057. const plane = clippingPlanes.element( i );
  11058. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11059. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11060. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  11061. } );
  11062. }
  11063. const numIntersectionPlanes = intersectionPlanes.length;
  11064. if ( numIntersectionPlanes > 0 ) {
  11065. const clippingPlanes = uniformArray( intersectionPlanes );
  11066. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  11067. Loop( numIntersectionPlanes, ( { i } ) => {
  11068. const plane = clippingPlanes.element( i );
  11069. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11070. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11071. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  11072. } );
  11073. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  11074. }
  11075. diffuseColor.a.mulAssign( clipOpacity );
  11076. diffuseColor.a.equal( 0.0 ).discard();
  11077. } )();
  11078. }
  11079. /**
  11080. * Setups the default clipping.
  11081. *
  11082. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11083. * @param {Array<Vector4>} unionPlanes - The union planes.
  11084. * @return {Node} The result node.
  11085. */
  11086. setupDefault( intersectionPlanes, unionPlanes ) {
  11087. return Fn( () => {
  11088. const numUnionPlanes = unionPlanes.length;
  11089. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11090. const clippingPlanes = uniformArray( unionPlanes );
  11091. Loop( numUnionPlanes, ( { i } ) => {
  11092. const plane = clippingPlanes.element( i );
  11093. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  11094. } );
  11095. }
  11096. const numIntersectionPlanes = intersectionPlanes.length;
  11097. if ( numIntersectionPlanes > 0 ) {
  11098. const clippingPlanes = uniformArray( intersectionPlanes );
  11099. const clipped = bool( true ).toVar( 'clipped' );
  11100. Loop( numIntersectionPlanes, ( { i } ) => {
  11101. const plane = clippingPlanes.element( i );
  11102. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  11103. } );
  11104. clipped.discard();
  11105. }
  11106. } )();
  11107. }
  11108. /**
  11109. * Setups hardware clipping.
  11110. *
  11111. * @param {Array<Vector4>} unionPlanes - The union planes.
  11112. * @param {NodeBuilder} builder - The current node builder.
  11113. * @return {Node} The result node.
  11114. */
  11115. setupHardwareClipping( unionPlanes, builder ) {
  11116. const numUnionPlanes = unionPlanes.length;
  11117. builder.enableHardwareClipping( numUnionPlanes );
  11118. return Fn( () => {
  11119. const clippingPlanes = uniformArray( unionPlanes );
  11120. const hw_clip_distances = builtin( builder.getClipDistance() );
  11121. Loop( numUnionPlanes, ( { i } ) => {
  11122. const plane = clippingPlanes.element( i );
  11123. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  11124. hw_clip_distances.element( i ).assign( distance );
  11125. } );
  11126. } )();
  11127. }
  11128. }
  11129. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  11130. ClippingNode.DEFAULT = 'default';
  11131. ClippingNode.HARDWARE = 'hardware';
  11132. /**
  11133. * TSL function for setting up the default clipping logic.
  11134. *
  11135. * @function
  11136. * @returns {ClippingNode}
  11137. */
  11138. const clipping = () => nodeObject( new ClippingNode() );
  11139. /**
  11140. * TSL function for setting up alpha to coverage.
  11141. *
  11142. * @function
  11143. * @returns {ClippingNode}
  11144. */
  11145. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  11146. /**
  11147. * TSL function for setting up hardware-based clipping.
  11148. *
  11149. * @function
  11150. * @returns {ClippingNode}
  11151. */
  11152. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  11153. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  11154. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  11155. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11156. 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 ) ) ) ) ) );
  11157. } );
  11158. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11159. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  11160. } );
  11161. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  11162. // Find the discretized derivatives of our coordinates
  11163. const maxDeriv = max$1(
  11164. length( dFdx( position.xyz ) ),
  11165. length( dFdy( position.xyz ) )
  11166. );
  11167. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  11168. // Find two nearest log-discretized noise scales
  11169. const pixScales = vec2(
  11170. exp2( floor( log2( pixScale ) ) ),
  11171. exp2( ceil( log2( pixScale ) ) )
  11172. );
  11173. // Compute alpha thresholds at our two noise scales
  11174. const alpha = vec2(
  11175. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  11176. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  11177. );
  11178. // Factor to interpolate lerp with
  11179. const lerpFactor = fract( log2( pixScale ) );
  11180. // Interpolate alpha threshold from noise at two scales
  11181. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  11182. // Pass into CDF to compute uniformly distrib threshold
  11183. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  11184. const cases = vec3(
  11185. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  11186. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  11187. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  11188. // Find our final, uniformly distributed alpha threshold (ατ)
  11189. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  11190. // Avoids ατ == 0. Could also do ατ =1-ατ
  11191. return clamp( threshold, 1.0e-6, 1.0 );
  11192. } ).setLayout( {
  11193. name: 'getAlphaHashThreshold',
  11194. type: 'float',
  11195. inputs: [
  11196. { name: 'position', type: 'vec3' }
  11197. ]
  11198. } );
  11199. /**
  11200. * Base class for all node materials.
  11201. *
  11202. * @augments Material
  11203. */
  11204. class NodeMaterial extends Material {
  11205. static get type() {
  11206. return 'NodeMaterial';
  11207. }
  11208. /**
  11209. * Represents the type of the node material.
  11210. *
  11211. * @type {String}
  11212. */
  11213. get type() {
  11214. return this.constructor.type;
  11215. }
  11216. set type( _value ) { /* */ }
  11217. /**
  11218. * Constructs a new node material.
  11219. */
  11220. constructor() {
  11221. super();
  11222. /**
  11223. * This flag can be used for type testing.
  11224. *
  11225. * @type {Boolean}
  11226. * @readonly
  11227. * @default true
  11228. */
  11229. this.isNodeMaterial = true;
  11230. /**
  11231. * Whether this material is affected by fog or not.
  11232. *
  11233. * @type {Boolean}
  11234. * @default true
  11235. */
  11236. this.fog = true;
  11237. /**
  11238. * Whether this material is affected by lights or not.
  11239. *
  11240. * @type {Boolean}
  11241. * @default false
  11242. */
  11243. this.lights = false;
  11244. /**
  11245. * Whether this material uses hardware clipping or not.
  11246. * This property is managed by the engine and should not be
  11247. * modified by apps.
  11248. *
  11249. * @type {Boolean}
  11250. * @default false
  11251. */
  11252. this.hardwareClipping = false;
  11253. /**
  11254. * Node materials which set their `lights` property to `true`
  11255. * are affected by all lights of the scene. Sometimes selective
  11256. * lighting is wanted which means only _some_ lights in the scene
  11257. * affect a material. This can be achieved by creating an instance
  11258. * of {@link module:LightsNode~LightsNode} with a list of selective
  11259. * lights and assign the node to this property.
  11260. *
  11261. * ```js
  11262. * const customLightsNode = lights( [ light1, light2 ] );
  11263. * material.lightsNode = customLightsNode;
  11264. * ```
  11265. *
  11266. * @type {LightsNode?}
  11267. * @default null
  11268. */
  11269. this.lightsNode = null;
  11270. /**
  11271. * The environment of node materials can be defined by an environment
  11272. * map assigned to the `envMap` property or by `Scene.environment`
  11273. * if the node material is a PBR material. This node property allows to overwrite
  11274. * the default behavior and define the environment with a custom node.
  11275. *
  11276. * ```js
  11277. * material.envNode = pmremTexture( renderTarget.texture );
  11278. * ```
  11279. *
  11280. * @type {Node<vec3>?}
  11281. * @default null
  11282. */
  11283. this.envNode = null;
  11284. /**
  11285. * The lighting of node materials might be influenced by ambient occlusion.
  11286. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11287. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11288. * the default and define the ambient occlusion with a custom node instead.
  11289. *
  11290. * If you don't want to overwrite the diffuse color but modify the existing
  11291. * values instead, use {@link module:MaterialNode.materialAO}.
  11292. *
  11293. * @type {Node<float>?}
  11294. * @default null
  11295. */
  11296. this.aoNode = null;
  11297. /**
  11298. * The diffuse color of node materials is by default inferred from the
  11299. * `color` and `map` properties. This node property allows to overwrite the default
  11300. * and define the diffuse color with a node instead.
  11301. *
  11302. * ```js
  11303. * material.colorNode = color( 0xff0000 ); // define red color
  11304. * ```
  11305. *
  11306. * If you don't want to overwrite the diffuse color but modify the existing
  11307. * values instead, use {@link module:MaterialNode.materialColor}.
  11308. *
  11309. * ```js
  11310. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11311. * ```
  11312. *
  11313. * @type {Node<vec3>?}
  11314. * @default null
  11315. */
  11316. this.colorNode = null;
  11317. /**
  11318. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11319. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11320. * and define the normals with a node instead.
  11321. *
  11322. * If you don't want to overwrite the normals but modify the existing values instead,
  11323. * use {@link module:MaterialNode.materialNormal}.
  11324. *
  11325. * @type {Node<vec3>?}
  11326. * @default null
  11327. */
  11328. this.normalNode = null;
  11329. /**
  11330. * The opacity of node materials is by default inferred from the `opacity`
  11331. * and `alphaMap` properties. This node property allows to overwrite the default
  11332. * and define the opacity with a node instead.
  11333. *
  11334. * If you don't want to overwrite the normals but modify the existing
  11335. * value instead, use {@link module:MaterialNode.materialOpacity}.
  11336. *
  11337. * @type {Node<float>?}
  11338. * @default null
  11339. */
  11340. this.opacityNode = null;
  11341. /**
  11342. * This node can be used to to implement a variety of filter-like effects. The idea is
  11343. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11344. * to create an arbitrary effect and then assign the node composition to this property.
  11345. * Everything behind the object using this material will now be affected by a filter.
  11346. *
  11347. * ```js
  11348. * const material = new NodeMaterial()
  11349. * material.transparent = true;
  11350. *
  11351. * // everything behind the object will be monochromatic
  11352. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  11353. * ```
  11354. *
  11355. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11356. *
  11357. * @type {Node<vec3>?}
  11358. * @default null
  11359. */
  11360. this.backdropNode = null;
  11361. /**
  11362. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11363. *
  11364. * @type {Node<float>?}
  11365. * @default null
  11366. */
  11367. this.backdropAlphaNode = null;
  11368. /**
  11369. * The alpha test of node materials is by default inferred from the `alphaTest`
  11370. * property. This node property allows to overwrite the default and define the
  11371. * alpha test with a node instead.
  11372. *
  11373. * If you don't want to overwrite the alpha test but modify the existing
  11374. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11375. *
  11376. * @type {Node<float>?}
  11377. * @default null
  11378. */
  11379. this.alphaTestNode = null;
  11380. /**
  11381. * The local vertex positions are computed based on multiple factors like the
  11382. * attribute data, morphing or skinning. This node property allows to overwrite
  11383. * the default and define local vertex positions with nodes instead.
  11384. *
  11385. * If you don't want to overwrite the vertex positions but modify the existing
  11386. * values instead, use {@link module:Position.positionLocal}.
  11387. *
  11388. *```js
  11389. * material.positionNode = positionLocal.add( displace );
  11390. * ```
  11391. *
  11392. * @type {Node<vec3>?}
  11393. * @default null
  11394. */
  11395. this.positionNode = null;
  11396. /**
  11397. * This node property is intended for logic which modifies geometry data once or per animation step.
  11398. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11399. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11400. * can be implemented.
  11401. *
  11402. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11403. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11404. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11405. * eventually assigned to `geometryNode`.
  11406. *
  11407. * @type {Function}
  11408. * @default null
  11409. */
  11410. this.geometryNode = null;
  11411. /**
  11412. * Allows to overwrite depth values in the fragment shader.
  11413. *
  11414. * @type {Node<float>?}
  11415. * @default null
  11416. */
  11417. this.depthNode = null;
  11418. /**
  11419. * Allows to overwrite the position used for shadow map rendering which
  11420. * is by default {@link module:Position.positionWorld}, the vertex position
  11421. * in world space.
  11422. *
  11423. * @type {Node<float>?}
  11424. * @default null
  11425. */
  11426. this.shadowPositionNode = null;
  11427. /**
  11428. * This node can be used to influence how an object using this node material
  11429. * receive shadows.
  11430. *
  11431. * ```js
  11432. * const totalShadows = float( 1 ).toVar();
  11433. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11434. * totalShadows.mulAssign( shadow );
  11435. * //return float( 1 ); // bypass received shadows
  11436. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11437. * } );
  11438. *
  11439. * @type {Node<vec4>?}
  11440. * @default null
  11441. */
  11442. this.receivedShadowNode = null;
  11443. /**
  11444. * This node can be used to influence how an object using this node material
  11445. * casts shadows. To apply a color to shadows, you can simply do:
  11446. *
  11447. * ```js
  11448. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11449. * ```
  11450. *
  11451. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11452. * is also common to use the property with `Fn` function so checks are performed
  11453. * per fragment.
  11454. *
  11455. * ```js
  11456. * materialCustomShadow.castShadowNode = Fn( () => {
  11457. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11458. * return materialColor;
  11459. * } )();
  11460. * ```
  11461. *
  11462. * @type {Node<vec4>?}
  11463. * @default null
  11464. */
  11465. this.castShadowNode = null;
  11466. /**
  11467. * This node can be used to define the final output of the material.
  11468. *
  11469. * TODO: Explain the differences to `fragmentNode`.
  11470. *
  11471. * @type {Node<vec4>?}
  11472. * @default null
  11473. */
  11474. this.outputNode = null;
  11475. /**
  11476. * MRT configuration is done on renderer or pass level. This node allows to
  11477. * overwrite what values are written into MRT targets on material level. This
  11478. * can be useful for implementing selective FX features that should only affect
  11479. * specific objects.
  11480. *
  11481. * @type {MRTNode?}
  11482. * @default null
  11483. */
  11484. this.mrtNode = null;
  11485. /**
  11486. * This node property can be used if you need complete freedom in implementing
  11487. * the fragment shader. Assigning a node will replace the built-in material
  11488. * logic used in the fragment stage.
  11489. *
  11490. * @type {Node<vec4>?}
  11491. * @default null
  11492. */
  11493. this.fragmentNode = null;
  11494. /**
  11495. * This node property can be used if you need complete freedom in implementing
  11496. * the vertex shader. Assigning a node will replace the built-in material logic
  11497. * used in the vertex stage.
  11498. *
  11499. * @type {Node<vec4>?}
  11500. * @default null
  11501. */
  11502. this.vertexNode = null;
  11503. }
  11504. /**
  11505. * Allows to define a custom cache key that influence the material key computation
  11506. * for render objects.
  11507. *
  11508. * @return {String} The custom cache key.
  11509. */
  11510. customProgramCacheKey() {
  11511. return this.type + getCacheKey$1( this );
  11512. }
  11513. /**
  11514. * Builds this material with the given node builder.
  11515. *
  11516. * @param {NodeBuilder} builder - The current node builder.
  11517. */
  11518. build( builder ) {
  11519. this.setup( builder );
  11520. }
  11521. /**
  11522. * Setups a node material observer with the given builder.
  11523. *
  11524. * @param {NodeBuilder} builder - The current node builder.
  11525. * @return {NodeMaterialObserver} The node material observer.
  11526. */
  11527. setupObserver( builder ) {
  11528. return new NodeMaterialObserver( builder );
  11529. }
  11530. /**
  11531. * Setups the vertex and fragment stage of this node material.
  11532. *
  11533. * @param {NodeBuilder} builder - The current node builder.
  11534. */
  11535. setup( builder ) {
  11536. builder.context.setupNormal = () => this.setupNormal( builder );
  11537. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11538. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11539. const renderer = builder.renderer;
  11540. const renderTarget = renderer.getRenderTarget();
  11541. // < VERTEX STAGE >
  11542. builder.addStack();
  11543. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11544. builder.stack.outputNode = vertexNode;
  11545. this.setupHardwareClipping( builder );
  11546. if ( this.geometryNode !== null ) {
  11547. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11548. }
  11549. builder.addFlow( 'vertex', builder.removeStack() );
  11550. // < FRAGMENT STAGE >
  11551. builder.addStack();
  11552. let resultNode;
  11553. const clippingNode = this.setupClipping( builder );
  11554. if ( this.depthWrite === true || this.depthTest === true ) {
  11555. // only write depth if depth buffer is configured
  11556. if ( renderTarget !== null ) {
  11557. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11558. } else {
  11559. if ( renderer.depth === true ) this.setupDepth( builder );
  11560. }
  11561. }
  11562. if ( this.fragmentNode === null ) {
  11563. this.setupDiffuseColor( builder );
  11564. this.setupVariants( builder );
  11565. const outgoingLightNode = this.setupLighting( builder );
  11566. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11567. // force unsigned floats - useful for RenderTargets
  11568. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11569. resultNode = this.setupOutput( builder, basicOutput );
  11570. // OUTPUT NODE
  11571. output.assign( resultNode );
  11572. //
  11573. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11574. // MRT
  11575. if ( renderTarget !== null ) {
  11576. const mrt = renderer.getMRT();
  11577. const materialMRT = this.mrtNode;
  11578. if ( mrt !== null ) {
  11579. resultNode = mrt;
  11580. if ( materialMRT !== null ) {
  11581. resultNode = mrt.merge( materialMRT );
  11582. }
  11583. } else if ( materialMRT !== null ) {
  11584. resultNode = materialMRT;
  11585. }
  11586. }
  11587. } else {
  11588. let fragmentNode = this.fragmentNode;
  11589. if ( fragmentNode.isOutputStructNode !== true ) {
  11590. fragmentNode = vec4( fragmentNode );
  11591. }
  11592. resultNode = this.setupOutput( builder, fragmentNode );
  11593. }
  11594. builder.stack.outputNode = resultNode;
  11595. builder.addFlow( 'fragment', builder.removeStack() );
  11596. // < OBSERVER >
  11597. builder.observer = this.setupObserver( builder );
  11598. }
  11599. /**
  11600. * Setups the clipping node.
  11601. *
  11602. * @param {NodeBuilder} builder - The current node builder.
  11603. * @return {ClippingNode} The clipping node.
  11604. */
  11605. setupClipping( builder ) {
  11606. if ( builder.clippingContext === null ) return null;
  11607. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11608. let result = null;
  11609. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11610. const samples = builder.renderer.samples;
  11611. if ( this.alphaToCoverage && samples > 1 ) {
  11612. // to be added to flow when the color/alpha value has been determined
  11613. result = clippingAlpha();
  11614. } else {
  11615. builder.stack.add( clipping() );
  11616. }
  11617. }
  11618. return result;
  11619. }
  11620. /**
  11621. * Setups the hardware clipping if available on the current device.
  11622. *
  11623. * @param {NodeBuilder} builder - The current node builder.
  11624. */
  11625. setupHardwareClipping( builder ) {
  11626. this.hardwareClipping = false;
  11627. if ( builder.clippingContext === null ) return;
  11628. const candidateCount = builder.clippingContext.unionPlanes.length;
  11629. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11630. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11631. builder.stack.add( hardwareClipping() );
  11632. this.hardwareClipping = true;
  11633. }
  11634. return;
  11635. }
  11636. /**
  11637. * Setups the depth of this material.
  11638. *
  11639. * @param {NodeBuilder} builder - The current node builder.
  11640. */
  11641. setupDepth( builder ) {
  11642. const { renderer, camera } = builder;
  11643. // Depth
  11644. let depthNode = this.depthNode;
  11645. if ( depthNode === null ) {
  11646. const mrt = renderer.getMRT();
  11647. if ( mrt && mrt.has( 'depth' ) ) {
  11648. depthNode = mrt.get( 'depth' );
  11649. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11650. if ( camera.isPerspectiveCamera ) {
  11651. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11652. } else {
  11653. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11654. }
  11655. }
  11656. }
  11657. if ( depthNode !== null ) {
  11658. depth.assign( depthNode ).append();
  11659. }
  11660. }
  11661. /**
  11662. * Setups the position node in view space. This method exists
  11663. * so derived node materials can modify the implementation e.g. sprite materials.
  11664. *
  11665. * @param {NodeBuilder} builder - The current node builder.
  11666. * @return {Node<vec3>} The position in view space.
  11667. */
  11668. setupPositionView( /*builder*/ ) {
  11669. return modelViewMatrix.mul( positionLocal ).xyz;
  11670. }
  11671. /**
  11672. * Setups the position in clip space.
  11673. *
  11674. * @param {NodeBuilder} builder - The current node builder.
  11675. * @return {Node<vec4>} The position in view space.
  11676. */
  11677. setupModelViewProjection( /*builder*/ ) {
  11678. return cameraProjectionMatrix.mul( positionView );
  11679. }
  11680. /**
  11681. * Setups the logic for the vertex stage.
  11682. *
  11683. * @param {NodeBuilder} builder - The current node builder.
  11684. * @return {Node<vec4>} The position in clip space.
  11685. */
  11686. setupVertex( builder ) {
  11687. builder.addStack();
  11688. this.setupPosition( builder );
  11689. builder.context.vertex = builder.removeStack();
  11690. return modelViewProjection;
  11691. }
  11692. /**
  11693. * Setups the computation of the position in local space.
  11694. *
  11695. * @param {NodeBuilder} builder - The current node builder.
  11696. * @return {Node<vec3>} The position in local space.
  11697. */
  11698. setupPosition( builder ) {
  11699. const { object, geometry } = builder;
  11700. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11701. morphReference( object ).append();
  11702. }
  11703. if ( object.isSkinnedMesh === true ) {
  11704. skinningReference( object ).append();
  11705. }
  11706. if ( this.displacementMap ) {
  11707. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11708. const displacementScale = materialReference( 'displacementScale', 'float' );
  11709. const displacementBias = materialReference( 'displacementBias', 'float' );
  11710. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11711. }
  11712. if ( object.isBatchedMesh ) {
  11713. batch( object ).append();
  11714. }
  11715. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11716. instancedMesh( object ).append();
  11717. }
  11718. if ( this.positionNode !== null ) {
  11719. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11720. }
  11721. return positionLocal;
  11722. }
  11723. /**
  11724. * Setups the computation of the material's diffuse color.
  11725. *
  11726. * @param {NodeBuilder} builder - The current node builder.
  11727. * @param {BufferGeometry} geometry - The geometry.
  11728. */
  11729. setupDiffuseColor( { object, geometry } ) {
  11730. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11731. // VERTEX COLORS
  11732. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11733. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11734. }
  11735. // Instanced colors
  11736. if ( object.instanceColor ) {
  11737. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11738. colorNode = instanceColor.mul( colorNode );
  11739. }
  11740. if ( object.isBatchedMesh && object._colorsTexture ) {
  11741. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11742. colorNode = batchColor.mul( colorNode );
  11743. }
  11744. // COLOR
  11745. diffuseColor.assign( colorNode );
  11746. // OPACITY
  11747. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11748. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11749. // ALPHA TEST
  11750. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11751. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11752. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11753. }
  11754. // ALPHA HASH
  11755. if ( this.alphaHash === true ) {
  11756. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11757. }
  11758. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11759. diffuseColor.a.assign( 1.0 );
  11760. }
  11761. }
  11762. /**
  11763. * Abstract interface method that can be implemented by derived materials
  11764. * to setup material-specific node variables.
  11765. *
  11766. * @abstract
  11767. * @param {NodeBuilder} builder - The current node builder.
  11768. */
  11769. setupVariants( /*builder*/ ) {
  11770. // Interface function.
  11771. }
  11772. /**
  11773. * Setups the outgoing light node variable
  11774. *
  11775. * @return {Node<vec3>} The outgoing light node.
  11776. */
  11777. setupOutgoingLight() {
  11778. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11779. }
  11780. /**
  11781. * Setups the normal node from the material.
  11782. *
  11783. * @return {Node<vec3>} The normal node.
  11784. */
  11785. setupNormal() {
  11786. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11787. }
  11788. /**
  11789. * Setups the environment node from the material.
  11790. *
  11791. * @param {NodeBuilder} builder - The current node builder.
  11792. * @return {Node<vec4>} The environment node.
  11793. */
  11794. setupEnvironment( /*builder*/ ) {
  11795. let node = null;
  11796. if ( this.envNode ) {
  11797. node = this.envNode;
  11798. } else if ( this.envMap ) {
  11799. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11800. }
  11801. return node;
  11802. }
  11803. /**
  11804. * Setups the light map node from the material.
  11805. *
  11806. * @param {NodeBuilder} builder - The current node builder.
  11807. * @return {Node<vec3>} The light map node.
  11808. */
  11809. setupLightMap( builder ) {
  11810. let node = null;
  11811. if ( builder.material.lightMap ) {
  11812. node = new IrradianceNode( materialLightMap );
  11813. }
  11814. return node;
  11815. }
  11816. /**
  11817. * Setups the lights node based on the scene, environment and material.
  11818. *
  11819. * @param {NodeBuilder} builder - The current node builder.
  11820. * @return {LightsNode} The lights node.
  11821. */
  11822. setupLights( builder ) {
  11823. const materialLightsNode = [];
  11824. //
  11825. const envNode = this.setupEnvironment( builder );
  11826. if ( envNode && envNode.isLightingNode ) {
  11827. materialLightsNode.push( envNode );
  11828. }
  11829. const lightMapNode = this.setupLightMap( builder );
  11830. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11831. materialLightsNode.push( lightMapNode );
  11832. }
  11833. if ( this.aoNode !== null || builder.material.aoMap ) {
  11834. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11835. materialLightsNode.push( new AONode( aoNode ) );
  11836. }
  11837. let lightsN = this.lightsNode || builder.lightsNode;
  11838. if ( materialLightsNode.length > 0 ) {
  11839. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11840. }
  11841. return lightsN;
  11842. }
  11843. /**
  11844. * This method should be implemented by most derived materials
  11845. * since it defines the material's lighting model.
  11846. *
  11847. * @abstract
  11848. * @param {NodeBuilder} builder - The current node builder.
  11849. * @return {LightingModel} The lighting model.
  11850. */
  11851. setupLightingModel( /*builder*/ ) {
  11852. // Interface function.
  11853. }
  11854. /**
  11855. * Setups the outgoing light node.
  11856. *
  11857. * @param {NodeBuilder} builder - The current node builder.
  11858. * @return {Node<vec3>} The outgoing light node.
  11859. */
  11860. setupLighting( builder ) {
  11861. const { material } = builder;
  11862. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11863. // OUTGOING LIGHT
  11864. const lights = this.lights === true || this.lightsNode !== null;
  11865. const lightsNode = lights ? this.setupLights( builder ) : null;
  11866. let outgoingLightNode = this.setupOutgoingLight( builder );
  11867. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11868. const lightingModel = this.setupLightingModel( builder );
  11869. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11870. } else if ( backdropNode !== null ) {
  11871. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11872. }
  11873. // EMISSIVE
  11874. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11875. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11876. outgoingLightNode = outgoingLightNode.add( emissive );
  11877. }
  11878. return outgoingLightNode;
  11879. }
  11880. /**
  11881. * Setups the output node.
  11882. *
  11883. * @param {NodeBuilder} builder - The current node builder.
  11884. * @param {Node<vec4>} outputNode - The existing output node.
  11885. * @return {Node<vec4>} The output node.
  11886. */
  11887. setupOutput( builder, outputNode ) {
  11888. // FOG
  11889. if ( this.fog === true ) {
  11890. const fogNode = builder.fogNode;
  11891. if ( fogNode ) {
  11892. output.assign( outputNode );
  11893. outputNode = vec4( fogNode );
  11894. }
  11895. }
  11896. return outputNode;
  11897. }
  11898. /**
  11899. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11900. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11901. * defining all material properties of the classic type in the node type.
  11902. *
  11903. * @param {Material} material - The material to copy properties with their values to this node material.
  11904. */
  11905. setDefaultValues( material ) {
  11906. // This approach is to reuse the native refreshUniforms*
  11907. // and turn available the use of features like transmission and environment in core
  11908. for ( const property in material ) {
  11909. const value = material[ property ];
  11910. if ( this[ property ] === undefined ) {
  11911. this[ property ] = value;
  11912. if ( value && value.clone ) this[ property ] = value.clone();
  11913. }
  11914. }
  11915. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11916. for ( const key in descriptors ) {
  11917. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11918. descriptors[ key ].get !== undefined ) {
  11919. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11920. }
  11921. }
  11922. }
  11923. /**
  11924. * Serializes this material to JSON.
  11925. *
  11926. * @param {(Object|String)?} meta - The meta information for serialization.
  11927. * @return {Object} The serialized node.
  11928. */
  11929. toJSON( meta ) {
  11930. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11931. if ( isRoot ) {
  11932. meta = {
  11933. textures: {},
  11934. images: {},
  11935. nodes: {}
  11936. };
  11937. }
  11938. const data = Material.prototype.toJSON.call( this, meta );
  11939. const nodeChildren = getNodeChildren( this );
  11940. data.inputNodes = {};
  11941. for ( const { property, childNode } of nodeChildren ) {
  11942. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11943. }
  11944. // TODO: Copied from Object3D.toJSON
  11945. function extractFromCache( cache ) {
  11946. const values = [];
  11947. for ( const key in cache ) {
  11948. const data = cache[ key ];
  11949. delete data.metadata;
  11950. values.push( data );
  11951. }
  11952. return values;
  11953. }
  11954. if ( isRoot ) {
  11955. const textures = extractFromCache( meta.textures );
  11956. const images = extractFromCache( meta.images );
  11957. const nodes = extractFromCache( meta.nodes );
  11958. if ( textures.length > 0 ) data.textures = textures;
  11959. if ( images.length > 0 ) data.images = images;
  11960. if ( nodes.length > 0 ) data.nodes = nodes;
  11961. }
  11962. return data;
  11963. }
  11964. /**
  11965. * Copies the properties of the given node material to this instance.
  11966. *
  11967. * @param {NodeMaterial} source - The material to copy.
  11968. * @return {NodeMaterial} A reference to this node material.
  11969. */
  11970. copy( source ) {
  11971. this.lightsNode = source.lightsNode;
  11972. this.envNode = source.envNode;
  11973. this.colorNode = source.colorNode;
  11974. this.normalNode = source.normalNode;
  11975. this.opacityNode = source.opacityNode;
  11976. this.backdropNode = source.backdropNode;
  11977. this.backdropAlphaNode = source.backdropAlphaNode;
  11978. this.alphaTestNode = source.alphaTestNode;
  11979. this.positionNode = source.positionNode;
  11980. this.geometryNode = source.geometryNode;
  11981. this.depthNode = source.depthNode;
  11982. this.shadowPositionNode = source.shadowPositionNode;
  11983. this.receivedShadowNode = source.receivedShadowNode;
  11984. this.castShadowNode = source.castShadowNode;
  11985. this.outputNode = source.outputNode;
  11986. this.mrtNode = source.mrtNode;
  11987. this.fragmentNode = source.fragmentNode;
  11988. this.vertexNode = source.vertexNode;
  11989. return super.copy( source );
  11990. }
  11991. }
  11992. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11993. /**
  11994. * Node material version of `LineBasicMaterial`.
  11995. *
  11996. * @augments NodeMaterial
  11997. */
  11998. class LineBasicNodeMaterial extends NodeMaterial {
  11999. static get type() {
  12000. return 'LineBasicNodeMaterial';
  12001. }
  12002. /**
  12003. * Constructs a new line basic node material.
  12004. *
  12005. * @param {Object?} parameters - The configuration parameter.
  12006. */
  12007. constructor( parameters ) {
  12008. super();
  12009. /**
  12010. * This flag can be used for type testing.
  12011. *
  12012. * @type {Boolean}
  12013. * @readonly
  12014. * @default true
  12015. */
  12016. this.isLineBasicNodeMaterial = true;
  12017. this.setDefaultValues( _defaultValues$d );
  12018. this.setValues( parameters );
  12019. }
  12020. }
  12021. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  12022. /**
  12023. * Node material version of `LineDashedMaterial`.
  12024. *
  12025. * @augments NodeMaterial
  12026. */
  12027. class LineDashedNodeMaterial extends NodeMaterial {
  12028. static get type() {
  12029. return 'LineDashedNodeMaterial';
  12030. }
  12031. /**
  12032. * Constructs a new line dashed node material.
  12033. *
  12034. * @param {Object?} parameters - The configuration parameter.
  12035. */
  12036. constructor( parameters ) {
  12037. super();
  12038. /**
  12039. * This flag can be used for type testing.
  12040. *
  12041. * @type {Boolean}
  12042. * @readonly
  12043. * @default true
  12044. */
  12045. this.isLineDashedNodeMaterial = true;
  12046. this.setDefaultValues( _defaultValues$c );
  12047. /**
  12048. * The dash offset.
  12049. *
  12050. * @type {Number}
  12051. * @default 0
  12052. */
  12053. this.dashOffset = 0;
  12054. /**
  12055. * The offset of dash materials is by default inferred from the `dashOffset`
  12056. * property. This node property allows to overwrite the default
  12057. * and define the offset with a node instead.
  12058. *
  12059. * If you don't want to overwrite the offset but modify the existing
  12060. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  12061. *
  12062. * @type {Node<float>?}
  12063. * @default null
  12064. */
  12065. this.offsetNode = null;
  12066. /**
  12067. * The scale of dash materials is by default inferred from the `scale`
  12068. * property. This node property allows to overwrite the default
  12069. * and define the scale with a node instead.
  12070. *
  12071. * If you don't want to overwrite the scale but modify the existing
  12072. * value instead, use {@link module:MaterialNode.materialLineScale}.
  12073. *
  12074. * @type {Node<float>?}
  12075. * @default null
  12076. */
  12077. this.dashScaleNode = null;
  12078. /**
  12079. * The dash size of dash materials is by default inferred from the `dashSize`
  12080. * property. This node property allows to overwrite the default
  12081. * and define the dash size with a node instead.
  12082. *
  12083. * If you don't want to overwrite the dash size but modify the existing
  12084. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  12085. *
  12086. * @type {Node<float>?}
  12087. * @default null
  12088. */
  12089. this.dashSizeNode = null;
  12090. /**
  12091. * The gap size of dash materials is by default inferred from the `gapSize`
  12092. * property. This node property allows to overwrite the default
  12093. * and define the gap size with a node instead.
  12094. *
  12095. * If you don't want to overwrite the gap size but modify the existing
  12096. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  12097. *
  12098. * @type {Node<float>?}
  12099. * @default null
  12100. */
  12101. this.gapSizeNode = null;
  12102. this.setValues( parameters );
  12103. }
  12104. /**
  12105. * Setups the dash specific node variables.
  12106. *
  12107. * @param {NodeBuilder} builder - The current node builder.
  12108. */
  12109. setupVariants( /* builder */ ) {
  12110. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12111. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12112. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12113. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12114. dashSize.assign( dashSizeNode );
  12115. gapSize.assign( gapSizeNode );
  12116. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  12117. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  12118. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  12119. }
  12120. }
  12121. /** @module ViewportSharedTextureNode **/
  12122. let _sharedFramebuffer = null;
  12123. /**
  12124. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  12125. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  12126. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  12127. *
  12128. * @augments module:ViewportTextureNode~ViewportTextureNode
  12129. */
  12130. class ViewportSharedTextureNode extends ViewportTextureNode {
  12131. static get type() {
  12132. return 'ViewportSharedTextureNode';
  12133. }
  12134. /**
  12135. * Constructs a new viewport shared texture node.
  12136. *
  12137. * @param {Node} [uvNode=screenUV] - The uv node.
  12138. * @param {Node?} [levelNode=null] - The level node.
  12139. */
  12140. constructor( uvNode = screenUV, levelNode = null ) {
  12141. if ( _sharedFramebuffer === null ) {
  12142. _sharedFramebuffer = new FramebufferTexture();
  12143. }
  12144. super( uvNode, levelNode, _sharedFramebuffer );
  12145. }
  12146. updateReference() {
  12147. return this;
  12148. }
  12149. }
  12150. /**
  12151. * TSL function for creating a shared viewport texture node.
  12152. *
  12153. * @function
  12154. * @param {Node} [uvNode=screenUV] - The uv node.
  12155. * @param {Node?} [levelNode=null] - The level node.
  12156. * @returns {ViewportSharedTextureNode}
  12157. */
  12158. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  12159. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  12160. /**
  12161. * This node material can be used to render lines with a size larger than one
  12162. * by representing them as instanced meshes.
  12163. *
  12164. * @augments NodeMaterial
  12165. */
  12166. class Line2NodeMaterial extends NodeMaterial {
  12167. static get type() {
  12168. return 'Line2NodeMaterial';
  12169. }
  12170. /**
  12171. * Constructs a new node material for wide line rendering.
  12172. *
  12173. * @param {Object?} parameters - The configuration parameter.
  12174. */
  12175. constructor( parameters = {} ) {
  12176. super();
  12177. /**
  12178. * This flag can be used for type testing.
  12179. *
  12180. * @type {Boolean}
  12181. * @readonly
  12182. * @default true
  12183. */
  12184. this.isLine2NodeMaterial = true;
  12185. this.setDefaultValues( _defaultValues$b );
  12186. /**
  12187. * Whether vertex colors should be used or not.
  12188. *
  12189. * @type {Boolean}
  12190. * @default false
  12191. */
  12192. this.useColor = parameters.vertexColors;
  12193. /**
  12194. * The dash offset.
  12195. *
  12196. * @type {Number}
  12197. * @default 0
  12198. */
  12199. this.dashOffset = 0;
  12200. /**
  12201. * The line width.
  12202. *
  12203. * @type {Number}
  12204. * @default 0
  12205. */
  12206. this.lineWidth = 1;
  12207. /**
  12208. * Defines the lines color.
  12209. *
  12210. * @type {Node<vec3>?}
  12211. * @default null
  12212. */
  12213. this.lineColorNode = null;
  12214. /**
  12215. * Defines the offset.
  12216. *
  12217. * @type {Node<float>?}
  12218. * @default null
  12219. */
  12220. this.offsetNode = null;
  12221. /**
  12222. * Defines the dash scale.
  12223. *
  12224. * @type {Node<float>?}
  12225. * @default null
  12226. */
  12227. this.dashScaleNode = null;
  12228. /**
  12229. * Defines the dash size.
  12230. *
  12231. * @type {Node<float>?}
  12232. * @default null
  12233. */
  12234. this.dashSizeNode = null;
  12235. /**
  12236. * Defines the gap size.
  12237. *
  12238. * @type {Node<float>?}
  12239. * @default null
  12240. */
  12241. this.gapSizeNode = null;
  12242. /**
  12243. * Blending is set to `NoBlending` since transparency
  12244. * is not supported, yet.
  12245. *
  12246. * @type {Number}
  12247. * @default 0
  12248. */
  12249. this.blending = NoBlending;
  12250. this._useDash = parameters.dashed;
  12251. this._useAlphaToCoverage = true;
  12252. this._useWorldUnits = false;
  12253. this.setValues( parameters );
  12254. }
  12255. /**
  12256. * Setups the vertex and fragment stage of this node material.
  12257. *
  12258. * @param {NodeBuilder} builder - The current node builder.
  12259. */
  12260. setup( builder ) {
  12261. const { renderer } = builder;
  12262. const useAlphaToCoverage = this._useAlphaToCoverage;
  12263. const useColor = this.useColor;
  12264. const useDash = this._useDash;
  12265. const useWorldUnits = this._useWorldUnits;
  12266. const trimSegment = Fn( ( { start, end } ) => {
  12267. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12268. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12269. const nearEstimate = b.mul( - 0.5 ).div( a );
  12270. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12271. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12272. } ).setLayout( {
  12273. name: 'trimSegment',
  12274. type: 'vec4',
  12275. inputs: [
  12276. { name: 'start', type: 'vec4' },
  12277. { name: 'end', type: 'vec4' }
  12278. ]
  12279. } );
  12280. this.vertexNode = Fn( () => {
  12281. const instanceStart = attribute( 'instanceStart' );
  12282. const instanceEnd = attribute( 'instanceEnd' );
  12283. // camera space
  12284. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12285. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12286. if ( useDash ) {
  12287. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12288. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12289. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12290. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12291. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12292. lineDistance = lineDistance.add( offsetNode );
  12293. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12294. }
  12295. if ( useWorldUnits ) {
  12296. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12297. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12298. }
  12299. const aspect = viewport.z.div( viewport.w );
  12300. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12301. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12302. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12303. // perhaps there is a more elegant solution -- WestLangley
  12304. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  12305. If( perspective, () => {
  12306. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12307. end.assign( trimSegment( { start: start, end: end } ) );
  12308. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12309. start.assign( trimSegment( { start: end, end: start } ) );
  12310. } );
  12311. } );
  12312. // clip space
  12313. const clipStart = cameraProjectionMatrix.mul( start );
  12314. const clipEnd = cameraProjectionMatrix.mul( end );
  12315. // ndc space
  12316. const ndcStart = clipStart.xyz.div( clipStart.w );
  12317. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12318. // direction
  12319. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12320. // account for clip-space aspect ratio
  12321. dir.x.assign( dir.x.mul( aspect ) );
  12322. dir.assign( dir.normalize() );
  12323. const clip = vec4().toVar();
  12324. if ( useWorldUnits ) {
  12325. // get the offset direction as perpendicular to the view vector
  12326. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12327. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12328. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12329. const worldFwd = worldDir.cross( worldUp );
  12330. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12331. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12332. // height offset
  12333. const hw = materialLineWidth.mul( 0.5 );
  12334. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12335. // don't extend the line if we're rendering dashes because we
  12336. // won't be rendering the endcaps
  12337. if ( ! useDash ) {
  12338. // cap extension
  12339. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12340. // add width to the box
  12341. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12342. // endcaps
  12343. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12344. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12345. } );
  12346. }
  12347. // project the worldpos
  12348. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12349. // shift the depth of the projected points so the line
  12350. // segments overlap neatly
  12351. const clipPose = vec3().toVar();
  12352. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12353. clip.z.assign( clipPose.z.mul( clip.w ) );
  12354. } else {
  12355. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12356. // undo aspect ratio adjustment
  12357. dir.x.assign( dir.x.div( aspect ) );
  12358. offset.x.assign( offset.x.div( aspect ) );
  12359. // sign flip
  12360. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12361. // endcaps
  12362. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12363. offset.assign( offset.sub( dir ) );
  12364. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12365. offset.assign( offset.add( dir ) );
  12366. } );
  12367. // adjust for linewidth
  12368. offset.assign( offset.mul( materialLineWidth ) );
  12369. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12370. offset.assign( offset.div( viewport.w ) );
  12371. // select end
  12372. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12373. // back to clip space
  12374. offset.assign( offset.mul( clip.w ) );
  12375. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12376. }
  12377. return clip;
  12378. } )();
  12379. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12380. const p13 = p1.sub( p3 );
  12381. const p43 = p4.sub( p3 );
  12382. const p21 = p2.sub( p1 );
  12383. const d1343 = p13.dot( p43 );
  12384. const d4321 = p43.dot( p21 );
  12385. const d1321 = p13.dot( p21 );
  12386. const d4343 = p43.dot( p43 );
  12387. const d2121 = p21.dot( p21 );
  12388. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12389. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12390. const mua = numer.div( denom ).clamp();
  12391. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12392. return vec2( mua, mub );
  12393. } );
  12394. this.colorNode = Fn( () => {
  12395. const vUv = uv();
  12396. if ( useDash ) {
  12397. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12398. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12399. dashSize.assign( dashSizeNode );
  12400. gapSize.assign( gapSizeNode );
  12401. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12402. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12403. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12404. }
  12405. const alpha = float( 1 ).toVar( 'alpha' );
  12406. if ( useWorldUnits ) {
  12407. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12408. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12409. // Find the closest points on the view ray and the line segment
  12410. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12411. const lineDir = worldEnd.sub( worldStart );
  12412. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12413. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12414. const p2 = rayEnd.mul( params.y );
  12415. const delta = p1.sub( p2 );
  12416. const len = delta.length();
  12417. const norm = len.div( materialLineWidth );
  12418. if ( ! useDash ) {
  12419. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12420. const dnorm = norm.fwidth();
  12421. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12422. } else {
  12423. norm.greaterThan( 0.5 ).discard();
  12424. }
  12425. }
  12426. } else {
  12427. // round endcaps
  12428. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12429. const a = vUv.x;
  12430. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12431. const len2 = a.mul( a ).add( b.mul( b ) );
  12432. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12433. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12434. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12435. } );
  12436. } else {
  12437. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12438. const a = vUv.x;
  12439. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12440. const len2 = a.mul( a ).add( b.mul( b ) );
  12441. len2.greaterThan( 1.0 ).discard();
  12442. } );
  12443. }
  12444. }
  12445. let lineColorNode;
  12446. if ( this.lineColorNode ) {
  12447. lineColorNode = this.lineColorNode;
  12448. } else {
  12449. if ( useColor ) {
  12450. const instanceColorStart = attribute( 'instanceColorStart' );
  12451. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12452. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12453. lineColorNode = instanceColor.mul( materialColor );
  12454. } else {
  12455. lineColorNode = materialColor;
  12456. }
  12457. }
  12458. return vec4( lineColorNode, alpha );
  12459. } )();
  12460. if ( this.transparent ) {
  12461. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12462. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12463. }
  12464. super.setup( builder );
  12465. }
  12466. /**
  12467. * Whether the lines should sized in world units or not.
  12468. * When set to `false` the unit is pixel.
  12469. *
  12470. * @type {Boolean}
  12471. * @default false
  12472. */
  12473. get worldUnits() {
  12474. return this._useWorldUnits;
  12475. }
  12476. set worldUnits( value ) {
  12477. if ( this._useWorldUnits !== value ) {
  12478. this._useWorldUnits = value;
  12479. this.needsUpdate = true;
  12480. }
  12481. }
  12482. /**
  12483. * Whether the lines should be dashed or not.
  12484. *
  12485. * @type {Boolean}
  12486. * @default false
  12487. */
  12488. get dashed() {
  12489. return this._useDash;
  12490. }
  12491. set dashed( value ) {
  12492. if ( this._useDash !== value ) {
  12493. this._useDash = value;
  12494. this.needsUpdate = true;
  12495. }
  12496. }
  12497. /**
  12498. * Whether alpha to coverage should be used or not.
  12499. *
  12500. * @type {Boolean}
  12501. * @default true
  12502. */
  12503. get alphaToCoverage() {
  12504. return this._useAlphaToCoverage;
  12505. }
  12506. set alphaToCoverage( value ) {
  12507. if ( this._useAlphaToCoverage !== value ) {
  12508. this._useAlphaToCoverage = value;
  12509. this.needsUpdate = true;
  12510. }
  12511. }
  12512. }
  12513. /** @module Packing **/
  12514. /**
  12515. * Packs a direction vector into a color value.
  12516. *
  12517. * @method
  12518. * @param {Node<vec3>} node - The direction to pack.
  12519. * @return {Node<vec3>} The color.
  12520. */
  12521. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12522. /**
  12523. * Unpacks a color value into a direction vector.
  12524. *
  12525. * @method
  12526. * @param {Node<vec3>} node - The color to unpack.
  12527. * @return {Node<vec3>} The direction.
  12528. */
  12529. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12530. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12531. /**
  12532. * Node material version of `MeshNormalMaterial`.
  12533. *
  12534. * @augments NodeMaterial
  12535. */
  12536. class MeshNormalNodeMaterial extends NodeMaterial {
  12537. static get type() {
  12538. return 'MeshNormalNodeMaterial';
  12539. }
  12540. /**
  12541. * Constructs a new mesh normal node material.
  12542. *
  12543. * @param {Object?} parameters - The configuration parameter.
  12544. */
  12545. constructor( parameters ) {
  12546. super();
  12547. /**
  12548. * This flag can be used for type testing.
  12549. *
  12550. * @type {Boolean}
  12551. * @readonly
  12552. * @default true
  12553. */
  12554. this.isMeshNormalNodeMaterial = true;
  12555. this.setDefaultValues( _defaultValues$a );
  12556. this.setValues( parameters );
  12557. }
  12558. /**
  12559. * Overwrites the default implementation by computing the diffuse color
  12560. * based on the normal data.
  12561. */
  12562. setupDiffuseColor() {
  12563. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12564. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12565. }
  12566. }
  12567. /** @module EquirectUVNode **/
  12568. /**
  12569. * Can be used to compute texture coordinates for projecting an
  12570. * equirectangular texture onto a mesh for using it as the scene's
  12571. * background.
  12572. *
  12573. * ```js
  12574. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12575. * ```
  12576. *
  12577. * @augments TempNode
  12578. */
  12579. class EquirectUVNode extends TempNode {
  12580. static get type() {
  12581. return 'EquirectUVNode';
  12582. }
  12583. /**
  12584. * Constructs a new equirect uv node.
  12585. *
  12586. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12587. */
  12588. constructor( dirNode = positionWorldDirection ) {
  12589. super( 'vec2' );
  12590. /**
  12591. * A direction vector for sampling why is by default `positionWorldDirection`.
  12592. *
  12593. * @type {Node<vec3>}
  12594. */
  12595. this.dirNode = dirNode;
  12596. }
  12597. setup() {
  12598. const dir = this.dirNode;
  12599. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12600. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12601. return vec2( u, v );
  12602. }
  12603. }
  12604. /**
  12605. * TSL function for creating an equirect uv node.
  12606. *
  12607. * @function
  12608. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12609. * @returns {EquirectUVNode}
  12610. */
  12611. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12612. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12613. /**
  12614. * This class represents a cube render target. It is a special version
  12615. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12616. *
  12617. * @augments WebGLCubeRenderTarget
  12618. */
  12619. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12620. constructor( size = 1, options = {} ) {
  12621. super( size, options );
  12622. this.isCubeRenderTarget = true;
  12623. }
  12624. /**
  12625. * Converts the given equirectangular texture to a cube map.
  12626. *
  12627. * @param {Renderer} renderer - The renderer.
  12628. * @param {Texture} texture - The equirectangular texture.
  12629. * @return {CubeRenderTarget} A reference to this cube render target.
  12630. */
  12631. fromEquirectangularTexture( renderer, texture$1 ) {
  12632. const currentMinFilter = texture$1.minFilter;
  12633. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12634. texture$1.generateMipmaps = true;
  12635. this.texture.type = texture$1.type;
  12636. this.texture.colorSpace = texture$1.colorSpace;
  12637. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12638. this.texture.minFilter = texture$1.minFilter;
  12639. this.texture.magFilter = texture$1.magFilter;
  12640. const geometry = new BoxGeometry( 5, 5, 5 );
  12641. const uvNode = equirectUV( positionWorldDirection );
  12642. const material = new NodeMaterial();
  12643. material.colorNode = texture( texture$1, uvNode, 0 );
  12644. material.side = BackSide;
  12645. material.blending = NoBlending;
  12646. const mesh = new Mesh( geometry, material );
  12647. const scene = new Scene();
  12648. scene.add( mesh );
  12649. // Avoid blurred poles
  12650. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12651. const camera = new CubeCamera( 1, 10, this );
  12652. const currentMRT = renderer.getMRT();
  12653. renderer.setMRT( null );
  12654. camera.update( renderer, scene );
  12655. renderer.setMRT( currentMRT );
  12656. texture$1.minFilter = currentMinFilter;
  12657. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12658. mesh.geometry.dispose();
  12659. mesh.material.dispose();
  12660. return this;
  12661. }
  12662. }
  12663. /** @module CubeMapNode **/
  12664. const _cache$1 = new WeakMap();
  12665. /**
  12666. * This node can be used to automatically convert environment maps in the
  12667. * equirectangular format into the cube map format.
  12668. *
  12669. * @augments TempNode
  12670. */
  12671. class CubeMapNode extends TempNode {
  12672. static get type() {
  12673. return 'CubeMapNode';
  12674. }
  12675. /**
  12676. * Constructs a new cube map node.
  12677. *
  12678. * @param {Node} envNode - The node representing the environment map.
  12679. */
  12680. constructor( envNode ) {
  12681. super( 'vec3' );
  12682. /**
  12683. * The node representing the environment map.
  12684. *
  12685. * @type {Node}
  12686. */
  12687. this.envNode = envNode;
  12688. /**
  12689. * A reference to the internal cube texture.
  12690. *
  12691. * @private
  12692. * @type {CubeTexture}
  12693. * @default null
  12694. */
  12695. this._cubeTexture = null;
  12696. /**
  12697. * A reference to the internal cube texture node.
  12698. *
  12699. * @private
  12700. * @type {CubeTextureNode}
  12701. */
  12702. this._cubeTextureNode = cubeTexture();
  12703. const defaultTexture = new CubeTexture();
  12704. defaultTexture.isRenderTargetTexture = true;
  12705. /**
  12706. * A default cube texture that acts as a placeholder.
  12707. * It is used when the conversion from equirectangular to cube
  12708. * map has not finished yet for a given texture.
  12709. *
  12710. * @private
  12711. * @type {CubeTexture}
  12712. */
  12713. this._defaultTexture = defaultTexture;
  12714. /**
  12715. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12716. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12717. *
  12718. * @type {String}
  12719. * @default 'render'
  12720. */
  12721. this.updateBeforeType = NodeUpdateType.RENDER;
  12722. }
  12723. updateBefore( frame ) {
  12724. const { renderer, material } = frame;
  12725. const envNode = this.envNode;
  12726. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12727. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12728. if ( texture && texture.isTexture ) {
  12729. const mapping = texture.mapping;
  12730. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12731. // check for converted cubemap map
  12732. if ( _cache$1.has( texture ) ) {
  12733. const cubeMap = _cache$1.get( texture );
  12734. mapTextureMapping( cubeMap, texture.mapping );
  12735. this._cubeTexture = cubeMap;
  12736. } else {
  12737. // create cube map from equirectangular map
  12738. const image = texture.image;
  12739. if ( isEquirectangularMapReady$1( image ) ) {
  12740. const renderTarget = new CubeRenderTarget( image.height );
  12741. renderTarget.fromEquirectangularTexture( renderer, texture );
  12742. mapTextureMapping( renderTarget.texture, texture.mapping );
  12743. this._cubeTexture = renderTarget.texture;
  12744. _cache$1.set( texture, renderTarget.texture );
  12745. texture.addEventListener( 'dispose', onTextureDispose );
  12746. } else {
  12747. // default cube texture as fallback when equirectangular texture is not yet loaded
  12748. this._cubeTexture = this._defaultTexture;
  12749. }
  12750. }
  12751. //
  12752. this._cubeTextureNode.value = this._cubeTexture;
  12753. } else {
  12754. // envNode already refers to a cube map
  12755. this._cubeTextureNode = this.envNode;
  12756. }
  12757. }
  12758. }
  12759. }
  12760. setup( builder ) {
  12761. this.updateBefore( builder );
  12762. return this._cubeTextureNode;
  12763. }
  12764. }
  12765. /**
  12766. * Returns true if the given equirectangular image has been fully loaded
  12767. * and is ready for further processing.
  12768. *
  12769. * @private
  12770. * @param {Image} image - The equirectangular image to check.
  12771. * @return {Boolean} Whether the image is ready or not.
  12772. */
  12773. function isEquirectangularMapReady$1( image ) {
  12774. if ( image === null || image === undefined ) return false;
  12775. return image.height > 0;
  12776. }
  12777. /**
  12778. * This function is executed when `dispose()` is called on the equirectangular
  12779. * texture. In this case, the generated cube map with its render target
  12780. * is deleted as well.
  12781. *
  12782. * @private
  12783. * @param {Object} event - The event object.
  12784. */
  12785. function onTextureDispose( event ) {
  12786. const texture = event.target;
  12787. texture.removeEventListener( 'dispose', onTextureDispose );
  12788. const renderTarget = _cache$1.get( texture );
  12789. if ( renderTarget !== undefined ) {
  12790. _cache$1.delete( texture );
  12791. renderTarget.dispose();
  12792. }
  12793. }
  12794. /**
  12795. * This function makes sure the generated cube map uses the correct
  12796. * texture mapping that corresponds to the equirectangular original.
  12797. *
  12798. * @private
  12799. * @param {Texture} texture - The cube texture.
  12800. * @param {Number} mapping - The original texture mapping.
  12801. */
  12802. function mapTextureMapping( texture, mapping ) {
  12803. if ( mapping === EquirectangularReflectionMapping ) {
  12804. texture.mapping = CubeReflectionMapping;
  12805. } else if ( mapping === EquirectangularRefractionMapping ) {
  12806. texture.mapping = CubeRefractionMapping;
  12807. }
  12808. }
  12809. /**
  12810. * TSL function for creating a cube map node.
  12811. *
  12812. * @function
  12813. * @param {Node} envNode - The node representing the environment map.
  12814. * @returns {CubeMapNode}
  12815. */
  12816. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12817. /**
  12818. * Represents a basic model for Image-based lighting (IBL). The environment
  12819. * is defined via environment maps in the equirectangular or cube map format.
  12820. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12821. * or {@link MeshPhongNodeMaterial}.
  12822. *
  12823. * @augments LightingNode
  12824. */
  12825. class BasicEnvironmentNode extends LightingNode {
  12826. static get type() {
  12827. return 'BasicEnvironmentNode';
  12828. }
  12829. /**
  12830. * Constructs a new basic environment node.
  12831. *
  12832. * @param {Node} [envNode=null] - A node representing the environment.
  12833. */
  12834. constructor( envNode = null ) {
  12835. super();
  12836. /**
  12837. * A node representing the environment.
  12838. *
  12839. * @type {Node}
  12840. * @default null
  12841. */
  12842. this.envNode = envNode;
  12843. }
  12844. setup( builder ) {
  12845. // environment property is used in the finish() method of BasicLightingModel
  12846. builder.context.environment = cubeMapNode( this.envNode );
  12847. }
  12848. }
  12849. /**
  12850. * A specific version of {@link IrradianceNode} that is only relevant
  12851. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12852. * requires a special scaling factor for the light map.
  12853. *
  12854. * @augments LightingNode
  12855. */
  12856. class BasicLightMapNode extends LightingNode {
  12857. static get type() {
  12858. return 'BasicLightMapNode';
  12859. }
  12860. /**
  12861. * Constructs a new basic light map node.
  12862. *
  12863. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12864. */
  12865. constructor( lightMapNode = null ) {
  12866. super();
  12867. /**
  12868. * The light map node.
  12869. *
  12870. * @type {Node<vec3>?}
  12871. */
  12872. this.lightMapNode = lightMapNode;
  12873. }
  12874. setup( builder ) {
  12875. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12876. const RECIPROCAL_PI = float( 1 / Math.PI );
  12877. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12878. }
  12879. }
  12880. /**
  12881. * Abstract class for implementing lighting models. The module defines
  12882. * multiple methods that concrete lighting models can implement. These
  12883. * methods are executed at different points during the light evaluation
  12884. * process.
  12885. */
  12886. class LightingModel {
  12887. /**
  12888. * This method is intended for setting up lighting model and context data
  12889. * which are later used in the evaluation process.
  12890. *
  12891. * @abstract
  12892. * @param {ContextNode} input - The current node context.
  12893. * @param {StackNode} stack - The current stack.
  12894. * @param {NodeBuilder} builder - The current node builder.
  12895. */
  12896. start( /*input, stack, builder*/ ) { }
  12897. /**
  12898. * This method is intended for executing final tasks like final updates
  12899. * to the outgoing light.
  12900. *
  12901. * @abstract
  12902. * @param {ContextNode} input - The current node context.
  12903. * @param {StackNode} stack - The current stack.
  12904. * @param {NodeBuilder} builder - The current node builder.
  12905. */
  12906. finish( /*input, stack, builder*/ ) { }
  12907. /**
  12908. * This method is intended for implementing the direct light term and
  12909. * executed during the build process of directional, point and spot light nodes.
  12910. *
  12911. * @abstract
  12912. * @param {Object} input - The input data.
  12913. * @param {StackNode} stack - The current stack.
  12914. * @param {NodeBuilder} builder - The current node builder.
  12915. */
  12916. direct( /*input, stack, builder*/ ) { }
  12917. /**
  12918. * This method is intended for implementing the direct light term for
  12919. * rect area light nodes.
  12920. *
  12921. * @abstract
  12922. * @param {Object} input - The input data.
  12923. * @param {StackNode} stack - The current stack.
  12924. * @param {NodeBuilder} builder - The current node builder.
  12925. */
  12926. directRectArea( /*input, stack, builder*/ ) {}
  12927. /**
  12928. * This method is intended for implementing the indirect light term.
  12929. *
  12930. * @abstract
  12931. * @param {ContextNode} input - The current node context.
  12932. * @param {StackNode} stack - The current stack.
  12933. * @param {NodeBuilder} builder - The current node builder.
  12934. */
  12935. indirect( /*input, stack, builder*/ ) { }
  12936. /**
  12937. * This method is intended for implementing the ambient occlusion term.
  12938. * Unlike other methods, this method must be called manually by the lighting
  12939. * model in its indirect term.
  12940. *
  12941. * @abstract
  12942. * @param {ContextNode} input - The current node context.
  12943. * @param {StackNode} stack - The current stack.
  12944. * @param {NodeBuilder} builder - The current node builder.
  12945. */
  12946. ambientOcclusion( /*input, stack, builder*/ ) { }
  12947. }
  12948. /**
  12949. * Represents the lighting model for unlit materials. The only light contribution
  12950. * is baked indirect lighting modulated with ambient occlusion and the material's
  12951. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12952. *
  12953. * @augments LightingModel
  12954. */
  12955. class BasicLightingModel extends LightingModel {
  12956. /**
  12957. * Constructs a new basic lighting model.
  12958. */
  12959. constructor() {
  12960. super();
  12961. }
  12962. /**
  12963. * Implements the baked indirect lighting with its modulation.
  12964. *
  12965. * @param {ContextNode} context - The current node context.
  12966. * @param {StackNode} stack - The current stack.
  12967. * @param {NodeBuilder} builder - The current node builder.
  12968. */
  12969. indirect( context, stack, builder ) {
  12970. const ambientOcclusion = context.ambientOcclusion;
  12971. const reflectedLight = context.reflectedLight;
  12972. const irradianceLightMap = builder.context.irradianceLightMap;
  12973. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12974. // accumulation (baked indirect lighting only)
  12975. if ( irradianceLightMap ) {
  12976. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12977. } else {
  12978. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12979. }
  12980. // modulation
  12981. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12982. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12983. }
  12984. /**
  12985. * Implements the environment mapping.
  12986. *
  12987. * @param {ContextNode} context - The current node context.
  12988. * @param {StackNode} stack - The current stack.
  12989. * @param {NodeBuilder} builder - The current node builder.
  12990. */
  12991. finish( context, stack, builder ) {
  12992. const material = builder.material;
  12993. const outgoingLight = context.outgoingLight;
  12994. const envNode = builder.context.environment;
  12995. if ( envNode ) {
  12996. switch ( material.combine ) {
  12997. case MultiplyOperation:
  12998. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12999. break;
  13000. case MixOperation:
  13001. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  13002. break;
  13003. case AddOperation:
  13004. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  13005. break;
  13006. default:
  13007. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  13008. break;
  13009. }
  13010. }
  13011. }
  13012. }
  13013. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  13014. /**
  13015. * Node material version of `MeshBasicMaterial`.
  13016. *
  13017. * @augments NodeMaterial
  13018. */
  13019. class MeshBasicNodeMaterial extends NodeMaterial {
  13020. static get type() {
  13021. return 'MeshBasicNodeMaterial';
  13022. }
  13023. /**
  13024. * Constructs a new mesh basic node material.
  13025. *
  13026. * @param {Object?} parameters - The configuration parameter.
  13027. */
  13028. constructor( parameters ) {
  13029. super();
  13030. /**
  13031. * This flag can be used for type testing.
  13032. *
  13033. * @type {Boolean}
  13034. * @readonly
  13035. * @default true
  13036. */
  13037. this.isMeshBasicNodeMaterial = true;
  13038. /**
  13039. * Although the basic material is by definition unlit, we set
  13040. * this property to `true` since we use a lighting model to compute
  13041. * the outgoing light of the fragment shader.
  13042. *
  13043. * @type {Boolean}
  13044. * @default true
  13045. */
  13046. this.lights = true;
  13047. this.setDefaultValues( _defaultValues$9 );
  13048. this.setValues( parameters );
  13049. }
  13050. /**
  13051. * Basic materials are not affected by normal and bump maps so we
  13052. * return by default {@link module:Normal.normalView}.
  13053. *
  13054. * @return {Node<vec3>} The normal node.
  13055. */
  13056. setupNormal() {
  13057. return normalView; // see #28839
  13058. }
  13059. /**
  13060. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13061. * to implement the default environment mapping.
  13062. *
  13063. * @param {NodeBuilder} builder - The current node builder.
  13064. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13065. */
  13066. setupEnvironment( builder ) {
  13067. const envNode = super.setupEnvironment( builder );
  13068. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13069. }
  13070. /**
  13071. * This method must be overwritten since light maps are evaluated
  13072. * with a special scaling factor for basic materials.
  13073. *
  13074. * @param {NodeBuilder} builder - The current node builder.
  13075. * @return {BasicLightMapNode<vec3>?} The light map node.
  13076. */
  13077. setupLightMap( builder ) {
  13078. let node = null;
  13079. if ( builder.material.lightMap ) {
  13080. node = new BasicLightMapNode( materialLightMap );
  13081. }
  13082. return node;
  13083. }
  13084. /**
  13085. * The material overwrites this method because `lights` is set to `true` but
  13086. * we still want to return the diffuse color as the outgoing light.
  13087. *
  13088. * @return {Node<vec3>} The outgoing light node.
  13089. */
  13090. setupOutgoingLight() {
  13091. return diffuseColor.rgb;
  13092. }
  13093. /**
  13094. * Setups the lighting model.
  13095. *
  13096. * @return {BasicLightingModel} The lighting model.
  13097. */
  13098. setupLightingModel() {
  13099. return new BasicLightingModel();
  13100. }
  13101. }
  13102. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  13103. // Original approximation by Christophe Schlick '94
  13104. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  13105. // Optimized variant (presented by Epic at SIGGRAPH '13)
  13106. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  13107. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  13108. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  13109. } ); // validated
  13110. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  13111. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  13112. } ); // validated
  13113. const G_BlinnPhong_Implicit = () => float( 0.25 );
  13114. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  13115. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  13116. } );
  13117. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13118. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13119. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13120. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13121. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  13122. const G = G_BlinnPhong_Implicit();
  13123. const D = D_BlinnPhong( { dotNH } );
  13124. return F.mul( G ).mul( D );
  13125. } );
  13126. /**
  13127. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  13128. *
  13129. * @augments BasicLightingModel
  13130. */
  13131. class PhongLightingModel extends BasicLightingModel {
  13132. /**
  13133. * Constructs a new phong lighting model.
  13134. *
  13135. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  13136. */
  13137. constructor( specular = true ) {
  13138. super();
  13139. /**
  13140. * Whether specular is supported or not. Set this to `false` if you are
  13141. * looking for a Lambert-like material meaning a material for non-shiny
  13142. * surfaces, without specular highlights.
  13143. *
  13144. * @type {Boolean}
  13145. * @default true
  13146. */
  13147. this.specular = specular;
  13148. }
  13149. /**
  13150. * Implements the direct lighting. The specular portion is optional an can be controlled
  13151. * with the {@link PhongLightingModel#specular} flag.
  13152. *
  13153. * @param {Object} input - The input data.
  13154. * @param {StackNode} stack - The current stack.
  13155. * @param {NodeBuilder} builder - The current node builder.
  13156. */
  13157. direct( { lightDirection, lightColor, reflectedLight } ) {
  13158. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13159. const irradiance = dotNL.mul( lightColor );
  13160. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13161. if ( this.specular === true ) {
  13162. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  13163. }
  13164. }
  13165. /**
  13166. * Implements the indirect lighting.
  13167. *
  13168. * @param {ContextNode} input - The current node context.
  13169. * @param {StackNode} stack - The current stack.
  13170. * @param {NodeBuilder} builder - The current node builder.
  13171. */
  13172. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  13173. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13174. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13175. }
  13176. }
  13177. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  13178. /**
  13179. * Node material version of `MeshLambertMaterial`.
  13180. *
  13181. * @augments NodeMaterial
  13182. */
  13183. class MeshLambertNodeMaterial extends NodeMaterial {
  13184. static get type() {
  13185. return 'MeshLambertNodeMaterial';
  13186. }
  13187. /**
  13188. * Constructs a new mesh lambert node material.
  13189. *
  13190. * @param {Object?} parameters - The configuration parameter.
  13191. */
  13192. constructor( parameters ) {
  13193. super();
  13194. /**
  13195. * This flag can be used for type testing.
  13196. *
  13197. * @type {Boolean}
  13198. * @readonly
  13199. * @default true
  13200. */
  13201. this.isMeshLambertNodeMaterial = true;
  13202. /**
  13203. * Set to `true` because lambert materials react on lights.
  13204. *
  13205. * @type {Boolean}
  13206. * @default true
  13207. */
  13208. this.lights = true;
  13209. this.setDefaultValues( _defaultValues$8 );
  13210. this.setValues( parameters );
  13211. }
  13212. /**
  13213. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13214. * to implement the default environment mapping.
  13215. *
  13216. * @param {NodeBuilder} builder - The current node builder.
  13217. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13218. */
  13219. setupEnvironment( builder ) {
  13220. const envNode = super.setupEnvironment( builder );
  13221. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13222. }
  13223. /**
  13224. * Setups the lighting model.
  13225. *
  13226. * @return {PhongLightingModel} The lighting model.
  13227. */
  13228. setupLightingModel( /*builder*/ ) {
  13229. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13230. }
  13231. }
  13232. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13233. /**
  13234. * Node material version of `MeshPhongMaterial`.
  13235. *
  13236. * @augments NodeMaterial
  13237. */
  13238. class MeshPhongNodeMaterial extends NodeMaterial {
  13239. static get type() {
  13240. return 'MeshPhongNodeMaterial';
  13241. }
  13242. /**
  13243. * Constructs a new mesh lambert node material.
  13244. *
  13245. * @param {Object?} parameters - The configuration parameter.
  13246. */
  13247. constructor( parameters ) {
  13248. super();
  13249. /**
  13250. * This flag can be used for type testing.
  13251. *
  13252. * @type {Boolean}
  13253. * @readonly
  13254. * @default true
  13255. */
  13256. this.isMeshPhongNodeMaterial = true;
  13257. /**
  13258. * Set to `true` because phong materials react on lights.
  13259. *
  13260. * @type {Boolean}
  13261. * @default true
  13262. */
  13263. this.lights = true;
  13264. /**
  13265. * The shininess of phong materials is by default inferred from the `shininess`
  13266. * property. This node property allows to overwrite the default
  13267. * and define the shininess with a node instead.
  13268. *
  13269. * If you don't want to overwrite the shininess but modify the existing
  13270. * value instead, use {@link module:MaterialNode.materialShininess}.
  13271. *
  13272. * @type {Node<float>?}
  13273. * @default null
  13274. */
  13275. this.shininessNode = null;
  13276. /**
  13277. * The specular color of phong materials is by default inferred from the
  13278. * `specular` property. This node property allows to overwrite the default
  13279. * and define the specular color with a node instead.
  13280. *
  13281. * If you don't want to overwrite the specular color but modify the existing
  13282. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13283. *
  13284. * @type {Node<vec3>?}
  13285. * @default null
  13286. */
  13287. this.specularNode = null;
  13288. this.setDefaultValues( _defaultValues$7 );
  13289. this.setValues( parameters );
  13290. }
  13291. /**
  13292. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13293. * to implement the default environment mapping.
  13294. *
  13295. * @param {NodeBuilder} builder - The current node builder.
  13296. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13297. */
  13298. setupEnvironment( builder ) {
  13299. const envNode = super.setupEnvironment( builder );
  13300. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13301. }
  13302. /**
  13303. * Setups the lighting model.
  13304. *
  13305. * @return {PhongLightingModel} The lighting model.
  13306. */
  13307. setupLightingModel( /*builder*/ ) {
  13308. return new PhongLightingModel();
  13309. }
  13310. /**
  13311. * Setups the phong specific node variables.
  13312. *
  13313. * @param {NodeBuilder} builder - The current node builder.
  13314. */
  13315. setupVariants( /*builder*/ ) {
  13316. // SHININESS
  13317. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13318. shininess.assign( shininessNode );
  13319. // SPECULAR COLOR
  13320. const specularNode = this.specularNode || materialSpecular;
  13321. specularColor.assign( specularNode );
  13322. }
  13323. copy( source ) {
  13324. this.shininessNode = source.shininessNode;
  13325. this.specularNode = source.specularNode;
  13326. return super.copy( source );
  13327. }
  13328. }
  13329. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13330. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13331. return float( 0 );
  13332. }
  13333. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13334. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13335. return geometryRoughness;
  13336. } );
  13337. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13338. const { roughness } = inputs;
  13339. const geometryRoughness = getGeometryRoughness();
  13340. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13341. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13342. roughnessFactor = roughnessFactor.min( 1.0 );
  13343. return roughnessFactor;
  13344. } );
  13345. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13346. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13347. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13348. const a2 = alpha.pow2();
  13349. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13350. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13351. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13352. } ).setLayout( {
  13353. name: 'V_GGX_SmithCorrelated',
  13354. type: 'float',
  13355. inputs: [
  13356. { name: 'alpha', type: 'float' },
  13357. { name: 'dotNL', type: 'float' },
  13358. { name: 'dotNV', type: 'float' }
  13359. ]
  13360. } ); // validated
  13361. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13362. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13363. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13364. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13365. const v = div( 0.5, gv.add( gl ) );
  13366. return v.saturate();
  13367. } ).setLayout( {
  13368. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13369. type: 'float',
  13370. inputs: [
  13371. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13372. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13373. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13374. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13375. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13376. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13377. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13378. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13379. ]
  13380. } );
  13381. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13382. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13383. // alpha is "roughness squared" in Disney’s reparameterization
  13384. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13385. const a2 = alpha.pow2();
  13386. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13387. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13388. } ).setLayout( {
  13389. name: 'D_GGX',
  13390. type: 'float',
  13391. inputs: [
  13392. { name: 'alpha', type: 'float' },
  13393. { name: 'dotNH', type: 'float' }
  13394. ]
  13395. } ); // validated
  13396. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13397. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13398. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13399. const a2 = alphaT.mul( alphaB );
  13400. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13401. const v2 = v.dot( v );
  13402. const w2 = a2.div( v2 );
  13403. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13404. } ).setLayout( {
  13405. name: 'D_GGX_Anisotropic',
  13406. type: 'float',
  13407. inputs: [
  13408. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13409. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13410. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13411. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13412. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13413. ]
  13414. } );
  13415. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13416. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13417. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13418. const normalView = inputs.normalView || transformedNormalView;
  13419. const alpha = roughness.pow2(); // UE4's roughness
  13420. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13421. const dotNL = normalView.dot( lightDirection ).clamp();
  13422. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13423. const dotNH = normalView.dot( halfDir ).clamp();
  13424. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13425. let F = F_Schlick( { f0, f90, dotVH } );
  13426. let V, D;
  13427. if ( defined( USE_IRIDESCENCE ) ) {
  13428. F = iridescence.mix( F, f );
  13429. }
  13430. if ( defined( USE_ANISOTROPY ) ) {
  13431. const dotTL = anisotropyT.dot( lightDirection );
  13432. const dotTV = anisotropyT.dot( positionViewDirection );
  13433. const dotTH = anisotropyT.dot( halfDir );
  13434. const dotBL = anisotropyB.dot( lightDirection );
  13435. const dotBV = anisotropyB.dot( positionViewDirection );
  13436. const dotBH = anisotropyB.dot( halfDir );
  13437. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13438. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13439. } else {
  13440. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13441. D = D_GGX( { alpha, dotNH } );
  13442. }
  13443. return F.mul( V ).mul( D );
  13444. } ); // validated
  13445. // Analytical approximation of the DFG LUT, one half of the
  13446. // split-sum approximation used in indirect specular lighting.
  13447. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13448. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13449. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13450. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  13451. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  13452. const r = roughness.mul( c0 ).add( c1 );
  13453. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  13454. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  13455. return fab;
  13456. } ).setLayout( {
  13457. name: 'DFGApprox',
  13458. type: 'vec2',
  13459. inputs: [
  13460. { name: 'roughness', type: 'float' },
  13461. { name: 'dotNV', type: 'vec3' }
  13462. ]
  13463. } );
  13464. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13465. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13466. const fab = DFGApprox( { dotNV, roughness } );
  13467. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13468. } );
  13469. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13470. const x = dotVH.oneMinus().saturate();
  13471. const x2 = x.mul( x );
  13472. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13473. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13474. } ).setLayout( {
  13475. name: 'Schlick_to_F0',
  13476. type: 'vec3',
  13477. inputs: [
  13478. { name: 'f', type: 'vec3' },
  13479. { name: 'f90', type: 'float' },
  13480. { name: 'dotVH', type: 'float' }
  13481. ]
  13482. } );
  13483. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13484. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13485. const alpha = roughness.pow2();
  13486. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13487. const invAlpha = float( 1.0 ).div( alpha );
  13488. const cos2h = dotNH.pow2();
  13489. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13490. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13491. } ).setLayout( {
  13492. name: 'D_Charlie',
  13493. type: 'float',
  13494. inputs: [
  13495. { name: 'roughness', type: 'float' },
  13496. { name: 'dotNH', type: 'float' }
  13497. ]
  13498. } );
  13499. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13500. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13501. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13502. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13503. } ).setLayout( {
  13504. name: 'V_Neubelt',
  13505. type: 'float',
  13506. inputs: [
  13507. { name: 'dotNV', type: 'float' },
  13508. { name: 'dotNL', type: 'float' }
  13509. ]
  13510. } );
  13511. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13512. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13513. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13514. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13515. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13516. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13517. const V = V_Neubelt( { dotNV, dotNL } );
  13518. return sheen.mul( D ).mul( V );
  13519. } );
  13520. // Rect Area Light
  13521. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13522. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13523. // code: https://github.com/selfshadow/ltc_code/
  13524. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13525. const LUT_SIZE = 64.0;
  13526. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13527. const LUT_BIAS = 0.5 / LUT_SIZE;
  13528. const dotNV = N.dot( V ).saturate();
  13529. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13530. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13531. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13532. return uv;
  13533. } ).setLayout( {
  13534. name: 'LTC_Uv',
  13535. type: 'vec2',
  13536. inputs: [
  13537. { name: 'N', type: 'vec3' },
  13538. { name: 'V', type: 'vec3' },
  13539. { name: 'roughness', type: 'float' }
  13540. ]
  13541. } );
  13542. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13543. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13544. // An approximation of the form factor of a horizon-clipped rectangle.
  13545. const l = f.length();
  13546. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13547. } ).setLayout( {
  13548. name: 'LTC_ClippedSphereFormFactor',
  13549. type: 'float',
  13550. inputs: [
  13551. { name: 'f', type: 'vec3' }
  13552. ]
  13553. } );
  13554. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13555. const x = v1.dot( v2 );
  13556. const y = x.abs().toVar();
  13557. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13558. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13559. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13560. const v = a.div( b );
  13561. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13562. return v1.cross( v2 ).mul( theta_sintheta );
  13563. } ).setLayout( {
  13564. name: 'LTC_EdgeVectorFormFactor',
  13565. type: 'vec3',
  13566. inputs: [
  13567. { name: 'v1', type: 'vec3' },
  13568. { name: 'v2', type: 'vec3' }
  13569. ]
  13570. } );
  13571. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13572. // bail if point is on back side of plane of light
  13573. // assumes ccw winding order of light vertices
  13574. const v1 = p1.sub( p0 ).toVar();
  13575. const v2 = p3.sub( p0 ).toVar();
  13576. const lightNormal = v1.cross( v2 );
  13577. const result = vec3().toVar();
  13578. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13579. // construct orthonormal basis around N
  13580. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13581. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13582. // compute transform
  13583. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13584. // transform rect
  13585. // & project rect onto sphere
  13586. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13587. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13588. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13589. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13590. // calculate vector form factor
  13591. const vectorFormFactor = vec3( 0 ).toVar();
  13592. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13593. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13594. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13595. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13596. // adjust for horizon clipping
  13597. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13598. } );
  13599. return result;
  13600. } ).setLayout( {
  13601. name: 'LTC_Evaluate',
  13602. type: 'vec3',
  13603. inputs: [
  13604. { name: 'N', type: 'vec3' },
  13605. { name: 'V', type: 'vec3' },
  13606. { name: 'P', type: 'vec3' },
  13607. { name: 'mInv', type: 'mat3' },
  13608. { name: 'p0', type: 'vec3' },
  13609. { name: 'p1', type: 'vec3' },
  13610. { name: 'p2', type: 'vec3' },
  13611. { name: 'p3', type: 'vec3' }
  13612. ]
  13613. } );
  13614. /** @module TextureBicubic **/
  13615. // Mipped Bicubic Texture Filtering by N8
  13616. // https://www.shadertoy.com/view/Dl2SDW
  13617. const bC = 1.0 / 6.0;
  13618. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13619. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13620. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13621. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13622. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13623. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13624. // h0 and h1 are the two offset functions
  13625. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13626. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13627. const bicubic = ( textureNode, texelSize, lod ) => {
  13628. const uv = textureNode.uvNode;
  13629. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13630. const iuv = floor( uvScaled );
  13631. const fuv = fract( uvScaled );
  13632. const g0x = g0( fuv.x );
  13633. const g1x = g1( fuv.x );
  13634. const h0x = h0( fuv.x );
  13635. const h1x = h1( fuv.x );
  13636. const h0y = h0( fuv.y );
  13637. const h1y = h1( fuv.y );
  13638. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13639. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13640. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13641. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13642. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13643. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13644. return a.add( b );
  13645. };
  13646. /**
  13647. * Applies mipped bicubic texture filtering to the given texture node.
  13648. *
  13649. * @method
  13650. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13651. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13652. * @return {Node} The filtered texture sample.
  13653. */
  13654. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13655. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13656. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13657. const fLodSizeInv = div( 1.0, fLodSize );
  13658. const cLodSizeInv = div( 1.0, cLodSize );
  13659. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13660. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13661. return fract( lodNode ).mix( fSample, cSample );
  13662. } );
  13663. //
  13664. // Transmission
  13665. //
  13666. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13667. // Direction of refracted light.
  13668. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13669. // Compute rotation-independent scaling of the model matrix.
  13670. const modelScale = vec3(
  13671. length( modelMatrix[ 0 ].xyz ),
  13672. length( modelMatrix[ 1 ].xyz ),
  13673. length( modelMatrix[ 2 ].xyz )
  13674. );
  13675. // The thickness is specified in local space.
  13676. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13677. } ).setLayout( {
  13678. name: 'getVolumeTransmissionRay',
  13679. type: 'vec3',
  13680. inputs: [
  13681. { name: 'n', type: 'vec3' },
  13682. { name: 'v', type: 'vec3' },
  13683. { name: 'thickness', type: 'float' },
  13684. { name: 'ior', type: 'float' },
  13685. { name: 'modelMatrix', type: 'mat4' }
  13686. ]
  13687. } );
  13688. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13689. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13690. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13691. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13692. } ).setLayout( {
  13693. name: 'applyIorToRoughness',
  13694. type: 'float',
  13695. inputs: [
  13696. { name: 'roughness', type: 'float' },
  13697. { name: 'ior', type: 'float' }
  13698. ]
  13699. } );
  13700. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13701. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13702. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13703. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13704. const transmissionSample = vTexture.sample( fragCoord );
  13705. //const transmissionSample = viewportMipTexture( fragCoord );
  13706. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13707. return textureBicubic( transmissionSample, lod );
  13708. } );
  13709. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13710. If( attenuationDistance.notEqual( 0 ), () => {
  13711. // Compute light attenuation using Beer's law.
  13712. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13713. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13714. return transmittance;
  13715. } );
  13716. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13717. return vec3( 1.0 );
  13718. } ).setLayout( {
  13719. name: 'volumeAttenuation',
  13720. type: 'vec3',
  13721. inputs: [
  13722. { name: 'transmissionDistance', type: 'float' },
  13723. { name: 'attenuationColor', type: 'vec3' },
  13724. { name: 'attenuationDistance', type: 'float' }
  13725. ]
  13726. } );
  13727. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13728. let transmittedLight, transmittance;
  13729. if ( dispersion ) {
  13730. transmittedLight = vec4().toVar();
  13731. transmittance = vec3().toVar();
  13732. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13733. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13734. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13735. const ior = iors.element( i );
  13736. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13737. const refractedRayExit = position.add( transmissionRay );
  13738. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13739. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13740. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13741. refractionCoords.addAssign( 1.0 );
  13742. refractionCoords.divAssign( 2.0 );
  13743. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13744. // Sample framebuffer to get pixel the refracted ray hits.
  13745. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13746. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13747. transmittedLight.a.addAssign( transmissionSample.a );
  13748. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13749. } );
  13750. transmittedLight.a.divAssign( 3.0 );
  13751. } else {
  13752. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13753. const refractedRayExit = position.add( transmissionRay );
  13754. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13755. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13756. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13757. refractionCoords.addAssign( 1.0 );
  13758. refractionCoords.divAssign( 2.0 );
  13759. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13760. // Sample framebuffer to get pixel the refracted ray hits.
  13761. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13762. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13763. }
  13764. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13765. const dotNV = n.dot( v ).clamp();
  13766. // Get the specular component.
  13767. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13768. dotNV,
  13769. specularColor,
  13770. specularF90,
  13771. roughness
  13772. } ) );
  13773. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13774. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13775. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13776. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13777. } );
  13778. //
  13779. // Iridescence
  13780. //
  13781. // XYZ to linear-sRGB color space
  13782. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13783. 3.2404542, - 0.9692660, 0.0556434,
  13784. - 1.5371385, 1.8760108, - 0.2040259,
  13785. - 0.4985314, 0.0415560, 1.0572252
  13786. );
  13787. // Assume air interface for top
  13788. // Note: We don't handle the case fresnel0 == 1
  13789. const Fresnel0ToIor = ( fresnel0 ) => {
  13790. const sqrtF0 = fresnel0.sqrt();
  13791. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13792. };
  13793. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13794. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13795. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13796. };
  13797. // Fresnel equations for dielectric/dielectric interfaces.
  13798. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13799. // Evaluation XYZ sensitivity curves in Fourier space
  13800. const evalSensitivity = ( OPD, shift ) => {
  13801. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13802. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13803. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13804. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13805. 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( - 4.5282e+09 ).exp() );
  13806. 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() );
  13807. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13808. const rgb = XYZ_TO_REC709.mul( xyz );
  13809. return rgb;
  13810. };
  13811. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13812. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13813. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13814. // Evaluate the cosTheta on the base layer (Snell law)
  13815. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13816. // Handle TIR:
  13817. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13818. If( cosTheta2Sq.lessThan( 0 ), () => {
  13819. return vec3( 1.0 );
  13820. } );
  13821. const cosTheta2 = cosTheta2Sq.sqrt();
  13822. // First interface
  13823. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13824. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13825. //const R21 = R12;
  13826. const T121 = R12.oneMinus();
  13827. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13828. const phi21 = float( Math.PI ).sub( phi12 );
  13829. // Second interface
  13830. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13831. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13832. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13833. const phi23 = vec3(
  13834. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13835. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13836. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13837. );
  13838. // Phase shift
  13839. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13840. const phi = vec3( phi21 ).add( phi23 );
  13841. // Compound terms
  13842. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13843. const r123 = R123.sqrt();
  13844. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13845. // Reflectance term for m = 0 (DC term amplitude)
  13846. const C0 = R12.add( Rs );
  13847. const I = C0.toVar();
  13848. // Reflectance term for m > 0 (pairs of diracs)
  13849. const Cm = Rs.sub( T121 ).toVar();
  13850. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13851. Cm.mulAssign( r123 );
  13852. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13853. I.addAssign( Cm.mul( Sm ) );
  13854. } );
  13855. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13856. return I.max( vec3( 0.0 ) );
  13857. } ).setLayout( {
  13858. name: 'evalIridescence',
  13859. type: 'vec3',
  13860. inputs: [
  13861. { name: 'outsideIOR', type: 'float' },
  13862. { name: 'eta2', type: 'float' },
  13863. { name: 'cosTheta1', type: 'float' },
  13864. { name: 'thinFilmThickness', type: 'float' },
  13865. { name: 'baseF0', type: 'vec3' }
  13866. ]
  13867. } );
  13868. //
  13869. // Sheen
  13870. //
  13871. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13872. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13873. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13874. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13875. const dotNV = normal.dot( viewDir ).saturate();
  13876. const r2 = roughness.pow2();
  13877. const a = select(
  13878. roughness.lessThan( 0.25 ),
  13879. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13880. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13881. );
  13882. const b = select(
  13883. roughness.lessThan( 0.25 ),
  13884. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13885. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13886. );
  13887. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13888. return DG.mul( 1.0 / Math.PI ).saturate();
  13889. } );
  13890. const clearcoatF0 = vec3( 0.04 );
  13891. const clearcoatF90 = float( 1 );
  13892. /**
  13893. * Represents the lighting model for a PBR material.
  13894. *
  13895. * @augments LightingModel
  13896. */
  13897. class PhysicalLightingModel extends LightingModel {
  13898. /**
  13899. * Constructs a new physical lighting model.
  13900. *
  13901. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13902. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13903. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13904. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13905. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13906. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13907. */
  13908. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13909. super();
  13910. /**
  13911. * Whether clearcoat is supported or not.
  13912. *
  13913. * @type {Boolean}
  13914. * @default false
  13915. */
  13916. this.clearcoat = clearcoat;
  13917. /**
  13918. * Whether sheen is supported or not.
  13919. *
  13920. * @type {Boolean}
  13921. * @default false
  13922. */
  13923. this.sheen = sheen;
  13924. /**
  13925. * Whether iridescence is supported or not.
  13926. *
  13927. * @type {Boolean}
  13928. * @default false
  13929. */
  13930. this.iridescence = iridescence;
  13931. /**
  13932. * Whether anisotropy is supported or not.
  13933. *
  13934. * @type {Boolean}
  13935. * @default false
  13936. */
  13937. this.anisotropy = anisotropy;
  13938. /**
  13939. * Whether transmission is supported or not.
  13940. *
  13941. * @type {Boolean}
  13942. * @default false
  13943. */
  13944. this.transmission = transmission;
  13945. /**
  13946. * Whether dispersion is supported or not.
  13947. *
  13948. * @type {Boolean}
  13949. * @default false
  13950. */
  13951. this.dispersion = dispersion;
  13952. /**
  13953. * The clear coat radiance.
  13954. *
  13955. * @type {Node?}
  13956. * @default null
  13957. */
  13958. this.clearcoatRadiance = null;
  13959. /**
  13960. * The clear coat specular direct.
  13961. *
  13962. * @type {Node?}
  13963. * @default null
  13964. */
  13965. this.clearcoatSpecularDirect = null;
  13966. /**
  13967. * The clear coat specular indirect.
  13968. *
  13969. * @type {Node?}
  13970. * @default null
  13971. */
  13972. this.clearcoatSpecularIndirect = null;
  13973. /**
  13974. * The sheen specular direct.
  13975. *
  13976. * @type {Node?}
  13977. * @default null
  13978. */
  13979. this.sheenSpecularDirect = null;
  13980. /**
  13981. * The sheen specular indirect.
  13982. *
  13983. * @type {Node?}
  13984. * @default null
  13985. */
  13986. this.sheenSpecularIndirect = null;
  13987. /**
  13988. * The iridescence Fresnel.
  13989. *
  13990. * @type {Node?}
  13991. * @default null
  13992. */
  13993. this.iridescenceFresnel = null;
  13994. /**
  13995. * The iridescence F0.
  13996. *
  13997. * @type {Node?}
  13998. * @default null
  13999. */
  14000. this.iridescenceF0 = null;
  14001. }
  14002. /**
  14003. * Depending on what features are requested, the method prepares certain node variables
  14004. * which are later used for lighting computations.
  14005. *
  14006. * @param {ContextNode} context - The current node context.
  14007. */
  14008. start( context ) {
  14009. if ( this.clearcoat === true ) {
  14010. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  14011. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  14012. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  14013. }
  14014. if ( this.sheen === true ) {
  14015. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  14016. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  14017. }
  14018. if ( this.iridescence === true ) {
  14019. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  14020. this.iridescenceFresnel = evalIridescence( {
  14021. outsideIOR: float( 1.0 ),
  14022. eta2: iridescenceIOR,
  14023. cosTheta1: dotNVi,
  14024. thinFilmThickness: iridescenceThickness,
  14025. baseF0: specularColor
  14026. } );
  14027. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  14028. }
  14029. if ( this.transmission === true ) {
  14030. const position = positionWorld;
  14031. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  14032. const n = transformedNormalWorld;
  14033. context.backdrop = getIBLVolumeRefraction(
  14034. n,
  14035. v,
  14036. roughness,
  14037. diffuseColor,
  14038. specularColor,
  14039. specularF90, // specularF90
  14040. position, // positionWorld
  14041. modelWorldMatrix, // modelMatrix
  14042. cameraViewMatrix, // viewMatrix
  14043. cameraProjectionMatrix, // projMatrix
  14044. ior,
  14045. thickness,
  14046. attenuationColor,
  14047. attenuationDistance,
  14048. this.dispersion ? dispersion : null
  14049. );
  14050. context.backdropAlpha = transmission;
  14051. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  14052. }
  14053. }
  14054. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  14055. // Approximates multi-scattering in order to preserve energy.
  14056. // http://www.jcgt.org/published/0008/01/03/
  14057. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  14058. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14059. const fab = DFGApprox( { roughness, dotNV } );
  14060. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  14061. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  14062. const Ess = fab.x.add( fab.y );
  14063. const Ems = Ess.oneMinus();
  14064. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  14065. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  14066. singleScatter.addAssign( FssEss );
  14067. multiScatter.addAssign( Fms.mul( Ems ) );
  14068. }
  14069. /**
  14070. * Implements the direct light.
  14071. *
  14072. * @param {Object} input - The input data.
  14073. * @param {StackNode} stack - The current stack.
  14074. * @param {NodeBuilder} builder - The current node builder.
  14075. */
  14076. direct( { lightDirection, lightColor, reflectedLight } ) {
  14077. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14078. const irradiance = dotNL.mul( lightColor );
  14079. if ( this.sheen === true ) {
  14080. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  14081. }
  14082. if ( this.clearcoat === true ) {
  14083. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  14084. const ccIrradiance = dotNLcc.mul( lightColor );
  14085. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  14086. }
  14087. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14088. 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 } ) ) );
  14089. }
  14090. /**
  14091. * This method is intended for implementing the direct light term for
  14092. * rect area light nodes.
  14093. *
  14094. * @param {Object} input - The input data.
  14095. * @param {StackNode} stack - The current stack.
  14096. * @param {NodeBuilder} builder - The current node builder.
  14097. */
  14098. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  14099. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  14100. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  14101. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  14102. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  14103. const N = transformedNormalView;
  14104. const V = positionViewDirection;
  14105. const P = positionView.toVar();
  14106. const uv = LTC_Uv( { N, V, roughness } );
  14107. const t1 = ltc_1.sample( uv ).toVar();
  14108. const t2 = ltc_2.sample( uv ).toVar();
  14109. const mInv = mat3(
  14110. vec3( t1.x, 0, t1.y ),
  14111. vec3( 0, 1, 0 ),
  14112. vec3( t1.z, 0, t1.w )
  14113. ).toVar();
  14114. // LTC Fresnel Approximation by Stephen Hill
  14115. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  14116. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  14117. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  14118. 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 } ) ) );
  14119. }
  14120. /**
  14121. * Implements the indirect lighting.
  14122. *
  14123. * @param {ContextNode} context - The current node context.
  14124. * @param {StackNode} stack - The current stack.
  14125. * @param {NodeBuilder} builder - The current node builder.
  14126. */
  14127. indirect( context, stack, builder ) {
  14128. this.indirectDiffuse( context, stack, builder );
  14129. this.indirectSpecular( context, stack, builder );
  14130. this.ambientOcclusion( context, stack, builder );
  14131. }
  14132. /**
  14133. * Implements the indirect diffuse term.
  14134. *
  14135. * @param {ContextNode} input - The current node context.
  14136. * @param {StackNode} stack - The current stack.
  14137. * @param {NodeBuilder} builder - The current node builder.
  14138. */
  14139. indirectDiffuse( { irradiance, reflectedLight } ) {
  14140. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14141. }
  14142. /**
  14143. * Implements the indirect specular term.
  14144. *
  14145. * @param {ContextNode} input - The current node context.
  14146. * @param {StackNode} stack - The current stack.
  14147. * @param {NodeBuilder} builder - The current node builder.
  14148. */
  14149. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  14150. if ( this.sheen === true ) {
  14151. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  14152. sheen,
  14153. IBLSheenBRDF( {
  14154. normal: transformedNormalView,
  14155. viewDir: positionViewDirection,
  14156. roughness: sheenRoughness
  14157. } )
  14158. ) );
  14159. }
  14160. if ( this.clearcoat === true ) {
  14161. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14162. const clearcoatEnv = EnvironmentBRDF( {
  14163. dotNV: dotNVcc,
  14164. specularColor: clearcoatF0,
  14165. specularF90: clearcoatF90,
  14166. roughness: clearcoatRoughness
  14167. } );
  14168. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  14169. }
  14170. // Both indirect specular and indirect diffuse light accumulate here
  14171. const singleScattering = vec3().toVar( 'singleScattering' );
  14172. const multiScattering = vec3().toVar( 'multiScattering' );
  14173. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  14174. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  14175. const totalScattering = singleScattering.add( multiScattering );
  14176. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  14177. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  14178. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  14179. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  14180. }
  14181. /**
  14182. * Implements the ambient occlusion term.
  14183. *
  14184. * @param {ContextNode} input - The current node context.
  14185. * @param {StackNode} stack - The current stack.
  14186. * @param {NodeBuilder} builder - The current node builder.
  14187. */
  14188. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  14189. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14190. const aoNV = dotNV.add( ambientOcclusion );
  14191. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  14192. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  14193. if ( this.clearcoat === true ) {
  14194. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  14195. }
  14196. if ( this.sheen === true ) {
  14197. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  14198. }
  14199. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14200. reflectedLight.indirectSpecular.mulAssign( aoNode );
  14201. }
  14202. /**
  14203. * Used for final lighting accumulations depending on the requested features.
  14204. *
  14205. * @param {ContextNode} context - The current node context.
  14206. * @param {StackNode} stack - The current stack.
  14207. * @param {NodeBuilder} builder - The current node builder.
  14208. */
  14209. finish( context ) {
  14210. const { outgoingLight } = context;
  14211. if ( this.clearcoat === true ) {
  14212. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14213. const Fcc = F_Schlick( {
  14214. dotVH: dotNVcc,
  14215. f0: clearcoatF0,
  14216. f90: clearcoatF90
  14217. } );
  14218. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14219. outgoingLight.assign( clearcoatLight );
  14220. }
  14221. if ( this.sheen === true ) {
  14222. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14223. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14224. outgoingLight.assign( sheenLight );
  14225. }
  14226. }
  14227. }
  14228. // These defines must match with PMREMGenerator
  14229. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14230. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  14231. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14232. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  14233. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14234. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14235. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14236. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14237. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14238. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14239. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14240. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14241. // These shader functions convert between the UV coordinates of a single face of
  14242. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14243. // sampling a textureCube (not generally normalized ).
  14244. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14245. const absDirection = vec3( abs( direction ) ).toVar();
  14246. const face = float( - 1.0 ).toVar();
  14247. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14248. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14249. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14250. } ).Else( () => {
  14251. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14252. } );
  14253. } ).Else( () => {
  14254. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14255. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14256. } ).Else( () => {
  14257. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14258. } );
  14259. } );
  14260. return face;
  14261. } ).setLayout( {
  14262. name: 'getFace',
  14263. type: 'float',
  14264. inputs: [
  14265. { name: 'direction', type: 'vec3' }
  14266. ]
  14267. } );
  14268. // RH coordinate system; PMREM face-indexing convention
  14269. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14270. const uv = vec2().toVar();
  14271. If( face.equal( 0.0 ), () => {
  14272. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14273. } ).ElseIf( face.equal( 1.0 ), () => {
  14274. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14275. } ).ElseIf( face.equal( 2.0 ), () => {
  14276. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14277. } ).ElseIf( face.equal( 3.0 ), () => {
  14278. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14279. } ).ElseIf( face.equal( 4.0 ), () => {
  14280. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14281. } ).Else( () => {
  14282. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14283. } );
  14284. return mul( 0.5, uv.add( 1.0 ) );
  14285. } ).setLayout( {
  14286. name: 'getUV',
  14287. type: 'vec2',
  14288. inputs: [
  14289. { name: 'direction', type: 'vec3' },
  14290. { name: 'face', type: 'float' }
  14291. ]
  14292. } );
  14293. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14294. const mip = float( 0.0 ).toVar();
  14295. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14296. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14297. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14298. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14299. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14300. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14301. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14302. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14303. } ).Else( () => {
  14304. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14305. } );
  14306. return mip;
  14307. } ).setLayout( {
  14308. name: 'roughnessToMip',
  14309. type: 'float',
  14310. inputs: [
  14311. { name: 'roughness', type: 'float' }
  14312. ]
  14313. } );
  14314. // RH coordinate system; PMREM face-indexing convention
  14315. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14316. const uv = uv_immutable.toVar();
  14317. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14318. const direction = vec3( uv, 1.0 ).toVar();
  14319. If( face.equal( 0.0 ), () => {
  14320. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14321. } ).ElseIf( face.equal( 1.0 ), () => {
  14322. direction.assign( direction.xzy );
  14323. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  14324. } ).ElseIf( face.equal( 2.0 ), () => {
  14325. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  14326. } ).ElseIf( face.equal( 3.0 ), () => {
  14327. direction.assign( direction.zyx );
  14328. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  14329. } ).ElseIf( face.equal( 4.0 ), () => {
  14330. direction.assign( direction.xzy );
  14331. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  14332. } ).ElseIf( face.equal( 5.0 ), () => {
  14333. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  14334. } );
  14335. return direction;
  14336. } ).setLayout( {
  14337. name: 'getDirection',
  14338. type: 'vec3',
  14339. inputs: [
  14340. { name: 'uv', type: 'vec2' },
  14341. { name: 'face', type: 'float' }
  14342. ]
  14343. } );
  14344. //
  14345. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14346. const roughness = float( roughness_immutable );
  14347. const sampleDir = vec3( sampleDir_immutable );
  14348. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14349. const mipF = fract( mip );
  14350. const mipInt = floor( mip );
  14351. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14352. If( mipF.notEqual( 0.0 ), () => {
  14353. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14354. color0.assign( mix( color0, color1, mipF ) );
  14355. } );
  14356. return color0;
  14357. } );
  14358. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14359. const mipInt = float( mipInt_immutable ).toVar();
  14360. const direction = vec3( direction_immutable );
  14361. const face = float( getFace( direction ) ).toVar();
  14362. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14363. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14364. const faceSize = float( exp2( mipInt ) ).toVar();
  14365. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14366. If( face.greaterThan( 2.0 ), () => {
  14367. uv.y.addAssign( faceSize );
  14368. face.subAssign( 3.0 );
  14369. } );
  14370. uv.x.addAssign( face.mul( faceSize ) );
  14371. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14372. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14373. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14374. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14375. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14376. } );
  14377. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14378. const cosTheta = cos( theta );
  14379. // Rodrigues' axis-angle rotation
  14380. const sampleDirection = outputDirection.mul( cosTheta )
  14381. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14382. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14383. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14384. } );
  14385. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14386. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14387. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14388. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14389. } );
  14390. axis.assign( normalize( axis ) );
  14391. const gl_FragColor = vec3().toVar();
  14392. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14393. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14394. If( i.greaterThanEqual( samples ), () => {
  14395. Break();
  14396. } );
  14397. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14398. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14399. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14400. } );
  14401. return vec4( gl_FragColor, 1 );
  14402. } );
  14403. /** @module PMREMNode **/
  14404. let _generator = null;
  14405. const _cache = new WeakMap();
  14406. /**
  14407. * Generates the cubeUV size based on the given image height.
  14408. *
  14409. * @private
  14410. * @param {Number} imageHeight - The image height.
  14411. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14412. */
  14413. function _generateCubeUVSize( imageHeight ) {
  14414. const maxMip = Math.log2( imageHeight ) - 2;
  14415. const texelHeight = 1.0 / imageHeight;
  14416. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14417. return { texelWidth, texelHeight, maxMip };
  14418. }
  14419. /**
  14420. * Generates a PMREM from the given texture .
  14421. *
  14422. * @private
  14423. * @param {Texture} texture - The texture to create the PMREM for.
  14424. * @return {Texture} The PMREM.
  14425. */
  14426. function _getPMREMFromTexture( texture ) {
  14427. let cacheTexture = _cache.get( texture );
  14428. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  14429. if ( pmremVersion !== texture.pmremVersion ) {
  14430. const image = texture.image;
  14431. if ( texture.isCubeTexture ) {
  14432. if ( isCubeMapReady( image ) ) {
  14433. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14434. } else {
  14435. return null;
  14436. }
  14437. } else {
  14438. if ( isEquirectangularMapReady( image ) ) {
  14439. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14440. } else {
  14441. return null;
  14442. }
  14443. }
  14444. cacheTexture.pmremVersion = texture.pmremVersion;
  14445. _cache.set( texture, cacheTexture );
  14446. }
  14447. return cacheTexture.texture;
  14448. }
  14449. /**
  14450. * This node represents a PMREM which is a special type of preprocessed
  14451. * environment map intended for PBR materials.
  14452. *
  14453. * ```js
  14454. * const material = new MeshStandardNodeMaterial();
  14455. * material.envNode = pmremTexture( envMap );
  14456. * ```
  14457. *
  14458. * @augments TempNode
  14459. */
  14460. class PMREMNode extends TempNode {
  14461. static get type() {
  14462. return 'PMREMNode';
  14463. }
  14464. /**
  14465. * Constructs a new function overloading node.
  14466. *
  14467. * @param {Texture} value - The input texture.
  14468. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14469. * @param {Node<float>} [levelNode=null] - The level node.
  14470. */
  14471. constructor( value, uvNode = null, levelNode = null ) {
  14472. super( 'vec3' );
  14473. /**
  14474. * Reference to the input texture.
  14475. *
  14476. * @private
  14477. * @type {Texture}
  14478. */
  14479. this._value = value;
  14480. /**
  14481. * Reference to the generated PMREM.
  14482. *
  14483. * @private
  14484. * @type {Texture | null}
  14485. * @default null
  14486. */
  14487. this._pmrem = null;
  14488. /**
  14489. * The uv node.
  14490. *
  14491. * @type {Node<vec2>}
  14492. */
  14493. this.uvNode = uvNode;
  14494. /**
  14495. * The level node.
  14496. *
  14497. * @type {Node<float>}
  14498. */
  14499. this.levelNode = levelNode;
  14500. /**
  14501. * Reference to a PMREM generator.
  14502. *
  14503. * @private
  14504. * @type {PMREMGenerator}
  14505. * @default null
  14506. */
  14507. this._generator = null;
  14508. const defaultTexture = new Texture();
  14509. defaultTexture.isRenderTargetTexture = true;
  14510. /**
  14511. * The texture node holding the generated PMREM.
  14512. *
  14513. * @private
  14514. * @type {TextureNode}
  14515. */
  14516. this._texture = texture( defaultTexture );
  14517. /**
  14518. * A uniform representing the PMREM's width.
  14519. *
  14520. * @private
  14521. * @type {UniformNode<float>}
  14522. */
  14523. this._width = uniform( 0 );
  14524. /**
  14525. * A uniform representing the PMREM's height.
  14526. *
  14527. * @private
  14528. * @type {UniformNode<float>}
  14529. */
  14530. this._height = uniform( 0 );
  14531. /**
  14532. * A uniform representing the PMREM's max Mip.
  14533. *
  14534. * @private
  14535. * @type {UniformNode<float>}
  14536. */
  14537. this._maxMip = uniform( 0 );
  14538. /**
  14539. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14540. *
  14541. * @type {String}
  14542. * @default 'render'
  14543. */
  14544. this.updateBeforeType = NodeUpdateType.RENDER;
  14545. }
  14546. set value( value ) {
  14547. this._value = value;
  14548. this._pmrem = null;
  14549. }
  14550. /**
  14551. * The node's texture value.
  14552. *
  14553. * @type {Texture}
  14554. */
  14555. get value() {
  14556. return this._value;
  14557. }
  14558. /**
  14559. * Uses the given PMREM texture to update internal values.
  14560. *
  14561. * @param {Texture} texture - The PMREM texture.
  14562. */
  14563. updateFromTexture( texture ) {
  14564. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14565. this._texture.value = texture;
  14566. this._width.value = cubeUVSize.texelWidth;
  14567. this._height.value = cubeUVSize.texelHeight;
  14568. this._maxMip.value = cubeUVSize.maxMip;
  14569. }
  14570. updateBefore() {
  14571. let pmrem = this._pmrem;
  14572. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  14573. const texture = this._value;
  14574. if ( pmremVersion !== texture.pmremVersion ) {
  14575. if ( texture.isPMREMTexture === true ) {
  14576. pmrem = texture;
  14577. } else {
  14578. pmrem = _getPMREMFromTexture( texture );
  14579. }
  14580. if ( pmrem !== null ) {
  14581. this._pmrem = pmrem;
  14582. this.updateFromTexture( pmrem );
  14583. }
  14584. }
  14585. }
  14586. setup( builder ) {
  14587. if ( _generator === null ) {
  14588. _generator = builder.createPMREMGenerator();
  14589. }
  14590. //
  14591. this.updateBefore( builder );
  14592. //
  14593. let uvNode = this.uvNode;
  14594. if ( uvNode === null && builder.context.getUV ) {
  14595. uvNode = builder.context.getUV( this );
  14596. }
  14597. //
  14598. const texture = this.value;
  14599. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14600. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14601. }
  14602. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14603. //
  14604. let levelNode = this.levelNode;
  14605. if ( levelNode === null && builder.context.getTextureLevel ) {
  14606. levelNode = builder.context.getTextureLevel( this );
  14607. }
  14608. //
  14609. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14610. }
  14611. }
  14612. /**
  14613. * Returns `true` if the given cube map image has been fully loaded.
  14614. *
  14615. * @private
  14616. * @param {Array<(Image|Object)>} image - The cube map image.
  14617. * @return {Boolean} Whether the given cube map is ready or not.
  14618. */
  14619. function isCubeMapReady( image ) {
  14620. if ( image === null || image === undefined ) return false;
  14621. let count = 0;
  14622. const length = 6;
  14623. for ( let i = 0; i < length; i ++ ) {
  14624. if ( image[ i ] !== undefined ) count ++;
  14625. }
  14626. return count === length;
  14627. }
  14628. /**
  14629. * Returns `true` if the given equirectangular image has been fully loaded.
  14630. *
  14631. * @private
  14632. * @param {(Image|Object)} image - The equirectangular image.
  14633. * @return {Boolean} Whether the given cube map is ready or not.
  14634. */
  14635. function isEquirectangularMapReady( image ) {
  14636. if ( image === null || image === undefined ) return false;
  14637. return image.height > 0;
  14638. }
  14639. /**
  14640. * TSL function for creating a PMREM node.
  14641. *
  14642. * @function
  14643. * @param {Texture} value - The input texture.
  14644. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14645. * @param {Node<float>} [levelNode=null] - The level node.
  14646. * @returns {PMREMNode}
  14647. */
  14648. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14649. const _envNodeCache = new WeakMap();
  14650. /**
  14651. * Represents a physical model for Image-based lighting (IBL). The environment
  14652. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14653. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14654. *
  14655. * @augments LightingNode
  14656. */
  14657. class EnvironmentNode extends LightingNode {
  14658. static get type() {
  14659. return 'EnvironmentNode';
  14660. }
  14661. /**
  14662. * Constructs a new environment node.
  14663. *
  14664. * @param {Node} [envNode=null] - A node representing the environment.
  14665. */
  14666. constructor( envNode = null ) {
  14667. super();
  14668. /**
  14669. * A node representing the environment.
  14670. *
  14671. * @type {Node?}
  14672. * @default null
  14673. */
  14674. this.envNode = envNode;
  14675. }
  14676. setup( builder ) {
  14677. const { material } = builder;
  14678. let envNode = this.envNode;
  14679. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14680. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14681. let cacheEnvNode = _envNodeCache.get( value );
  14682. if ( cacheEnvNode === undefined ) {
  14683. cacheEnvNode = pmremTexture( value );
  14684. _envNodeCache.set( value, cacheEnvNode );
  14685. }
  14686. envNode = cacheEnvNode;
  14687. }
  14688. //
  14689. const envMap = material.envMap;
  14690. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14691. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14692. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14693. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14694. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14695. const isolateRadiance = cache( radiance );
  14696. const isolateIrradiance = cache( irradiance );
  14697. //
  14698. builder.context.radiance.addAssign( isolateRadiance );
  14699. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14700. //
  14701. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14702. if ( clearcoatRadiance ) {
  14703. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14704. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14705. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14706. }
  14707. }
  14708. }
  14709. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14710. let reflectVec = null;
  14711. return {
  14712. getUV: () => {
  14713. if ( reflectVec === null ) {
  14714. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14715. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14716. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14717. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14718. }
  14719. return reflectVec;
  14720. },
  14721. getTextureLevel: () => {
  14722. return roughnessNode;
  14723. }
  14724. };
  14725. };
  14726. const createIrradianceContext = ( normalWorldNode ) => {
  14727. return {
  14728. getUV: () => {
  14729. return normalWorldNode;
  14730. },
  14731. getTextureLevel: () => {
  14732. return float( 1.0 );
  14733. }
  14734. };
  14735. };
  14736. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14737. /**
  14738. * Node material version of `MeshStandardMaterial`.
  14739. *
  14740. * @augments NodeMaterial
  14741. */
  14742. class MeshStandardNodeMaterial extends NodeMaterial {
  14743. static get type() {
  14744. return 'MeshStandardNodeMaterial';
  14745. }
  14746. /**
  14747. * Constructs a new mesh standard node material.
  14748. *
  14749. * @param {Object?} parameters - The configuration parameter.
  14750. */
  14751. constructor( parameters ) {
  14752. super();
  14753. /**
  14754. * This flag can be used for type testing.
  14755. *
  14756. * @type {Boolean}
  14757. * @readonly
  14758. * @default true
  14759. */
  14760. this.isMeshStandardNodeMaterial = true;
  14761. /**
  14762. * Set to `true` because standard materials react on lights.
  14763. *
  14764. * @type {Boolean}
  14765. * @default true
  14766. */
  14767. this.lights = true;
  14768. /**
  14769. * The emissive color of standard materials is by default inferred from the `emissive`,
  14770. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14771. * overwrite the default and define the emissive color with a node instead.
  14772. *
  14773. * If you don't want to overwrite the emissive color but modify the existing
  14774. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14775. *
  14776. * @type {Node<vec3>?}
  14777. * @default null
  14778. */
  14779. this.emissiveNode = null;
  14780. /**
  14781. * The metalness of standard materials is by default inferred from the `metalness`,
  14782. * and `metalnessMap` properties. This node property allows to
  14783. * overwrite the default and define the metalness with a node instead.
  14784. *
  14785. * If you don't want to overwrite the metalness but modify the existing
  14786. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14787. *
  14788. * @type {Node<float>?}
  14789. * @default null
  14790. */
  14791. this.metalnessNode = null;
  14792. /**
  14793. * The roughness of standard materials is by default inferred from the `roughness`,
  14794. * and `roughnessMap` properties. This node property allows to
  14795. * overwrite the default and define the roughness with a node instead.
  14796. *
  14797. * If you don't want to overwrite the roughness but modify the existing
  14798. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14799. *
  14800. * @type {Node<float>?}
  14801. * @default null
  14802. */
  14803. this.roughnessNode = null;
  14804. this.setDefaultValues( _defaultValues$6 );
  14805. this.setValues( parameters );
  14806. }
  14807. /**
  14808. * Overwritten since this type of material uses {@link EnvironmentNode}
  14809. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14810. * method honors `Scene.environment`.
  14811. *
  14812. * @param {NodeBuilder} builder - The current node builder.
  14813. * @return {EnvironmentNode<vec3>?} The environment node.
  14814. */
  14815. setupEnvironment( builder ) {
  14816. let envNode = super.setupEnvironment( builder );
  14817. if ( envNode === null && builder.environmentNode ) {
  14818. envNode = builder.environmentNode;
  14819. }
  14820. return envNode ? new EnvironmentNode( envNode ) : null;
  14821. }
  14822. /**
  14823. * Setups the lighting model.
  14824. *
  14825. * @return {PhysicalLightingModel} The lighting model.
  14826. */
  14827. setupLightingModel( /*builder*/ ) {
  14828. return new PhysicalLightingModel();
  14829. }
  14830. /**
  14831. * Setups the specular related node variables.
  14832. */
  14833. setupSpecular() {
  14834. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14835. specularColor.assign( specularColorNode );
  14836. specularF90.assign( 1.0 );
  14837. }
  14838. /**
  14839. * Setups the standard specific node variables.
  14840. *
  14841. * @param {NodeBuilder} builder - The current node builder.
  14842. */
  14843. setupVariants() {
  14844. // METALNESS
  14845. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14846. metalness.assign( metalnessNode );
  14847. // ROUGHNESS
  14848. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14849. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14850. roughness.assign( roughnessNode );
  14851. // SPECULAR COLOR
  14852. this.setupSpecular();
  14853. // DIFFUSE COLOR
  14854. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14855. }
  14856. copy( source ) {
  14857. this.emissiveNode = source.emissiveNode;
  14858. this.metalnessNode = source.metalnessNode;
  14859. this.roughnessNode = source.roughnessNode;
  14860. return super.copy( source );
  14861. }
  14862. }
  14863. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14864. /**
  14865. * Node material version of `MeshPhysicalMaterial`.
  14866. *
  14867. * @augments MeshStandardNodeMaterial
  14868. */
  14869. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14870. static get type() {
  14871. return 'MeshPhysicalNodeMaterial';
  14872. }
  14873. /**
  14874. * Constructs a new mesh physical node material.
  14875. *
  14876. * @param {Object?} parameters - The configuration parameter.
  14877. */
  14878. constructor( parameters ) {
  14879. super();
  14880. /**
  14881. * This flag can be used for type testing.
  14882. *
  14883. * @type {Boolean}
  14884. * @readonly
  14885. * @default true
  14886. */
  14887. this.isMeshPhysicalNodeMaterial = true;
  14888. /**
  14889. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14890. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14891. * and define the clearcoat with a node instead.
  14892. *
  14893. * If you don't want to overwrite the clearcoat but modify the existing
  14894. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14895. *
  14896. * @type {Node<float>?}
  14897. * @default null
  14898. */
  14899. this.clearcoatNode = null;
  14900. /**
  14901. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14902. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14903. * and define the clearcoat roughness with a node instead.
  14904. *
  14905. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14906. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14907. *
  14908. * @type {Node<float>?}
  14909. * @default null
  14910. */
  14911. this.clearcoatRoughnessNode = null;
  14912. /**
  14913. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14914. * property. This node property allows to overwrite the default
  14915. * and define the clearcoat normal with a node instead.
  14916. *
  14917. * If you don't want to overwrite the clearcoat normal but modify the existing
  14918. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14919. *
  14920. * @type {Node<vec3>?}
  14921. * @default null
  14922. */
  14923. this.clearcoatNormalNode = null;
  14924. /**
  14925. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14926. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14927. * and define the sheen with a node instead.
  14928. *
  14929. * If you don't want to overwrite the sheen but modify the existing
  14930. * value instead, use {@link module:MaterialNode.materialSheen}.
  14931. *
  14932. * @type {Node<vec3>?}
  14933. * @default null
  14934. */
  14935. this.sheenNode = null;
  14936. /**
  14937. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14938. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14939. * and define the sheen roughness with a node instead.
  14940. *
  14941. * If you don't want to overwrite the sheen roughness but modify the existing
  14942. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14943. *
  14944. * @type {Node<float>?}
  14945. * @default null
  14946. */
  14947. this.sheenRoughnessNode = null;
  14948. /**
  14949. * The iridescence of physical materials is by default inferred from the `iridescence`
  14950. * property. This node property allows to overwrite the default
  14951. * and define the iridescence with a node instead.
  14952. *
  14953. * If you don't want to overwrite the iridescence but modify the existing
  14954. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14955. *
  14956. * @type {Node<float>?}
  14957. * @default null
  14958. */
  14959. this.iridescenceNode = null;
  14960. /**
  14961. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14962. * property. This node property allows to overwrite the default
  14963. * and define the iridescence IOR with a node instead.
  14964. *
  14965. * If you don't want to overwrite the iridescence IOR but modify the existing
  14966. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14967. *
  14968. * @type {Node<float>?}
  14969. * @default null
  14970. */
  14971. this.iridescenceIORNode = null;
  14972. /**
  14973. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14974. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14975. * and define the iridescence thickness with a node instead.
  14976. *
  14977. * If you don't want to overwrite the iridescence thickness but modify the existing
  14978. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14979. *
  14980. * @type {Node<float>?}
  14981. * @default null
  14982. */
  14983. this.iridescenceThicknessNode = null;
  14984. /**
  14985. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14986. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14987. * and define the specular intensity with a node instead.
  14988. *
  14989. * If you don't want to overwrite the specular intensity but modify the existing
  14990. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14991. *
  14992. * @type {Node<float>?}
  14993. * @default null
  14994. */
  14995. this.specularIntensityNode = null;
  14996. /**
  14997. * The specular color of physical materials is by default inferred from the `specularColor`
  14998. * and `specularColorMap` properties. This node property allows to overwrite the default
  14999. * and define the specular color with a node instead.
  15000. *
  15001. * If you don't want to overwrite the specular color but modify the existing
  15002. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  15003. *
  15004. * @type {Node<vec3>?}
  15005. * @default null
  15006. */
  15007. this.specularColorNode = null;
  15008. /**
  15009. * The ior of physical materials is by default inferred from the `ior`
  15010. * property. This node property allows to overwrite the default
  15011. * and define the ior with a node instead.
  15012. *
  15013. * If you don't want to overwrite the ior but modify the existing
  15014. * value instead, use {@link module:MaterialNode.materialIOR}.
  15015. *
  15016. * @type {Node<float>?}
  15017. * @default null
  15018. */
  15019. this.iorNode = null;
  15020. /**
  15021. * The transmission of physical materials is by default inferred from the `transmission` and
  15022. * `transmissionMap` properties. This node property allows to overwrite the default
  15023. * and define the transmission with a node instead.
  15024. *
  15025. * If you don't want to overwrite the transmission but modify the existing
  15026. * value instead, use {@link module:MaterialNode.materialTransmission}.
  15027. *
  15028. * @type {Node<float>?}
  15029. * @default null
  15030. */
  15031. this.transmissionNode = null;
  15032. /**
  15033. * The thickness of physical materials is by default inferred from the `thickness` and
  15034. * `thicknessMap` properties. This node property allows to overwrite the default
  15035. * and define the thickness with a node instead.
  15036. *
  15037. * If you don't want to overwrite the thickness but modify the existing
  15038. * value instead, use {@link module:MaterialNode.materialThickness}.
  15039. *
  15040. * @type {Node<float>?}
  15041. * @default null
  15042. */
  15043. this.thicknessNode = null;
  15044. /**
  15045. * The attenuation distance of physical materials is by default inferred from the
  15046. * `attenuationDistance` property. This node property allows to overwrite the default
  15047. * and define the attenuation distance with a node instead.
  15048. *
  15049. * If you don't want to overwrite the attenuation distance but modify the existing
  15050. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  15051. *
  15052. * @type {Node<float>?}
  15053. * @default null
  15054. */
  15055. this.attenuationDistanceNode = null;
  15056. /**
  15057. * The attenuation color of physical materials is by default inferred from the
  15058. * `attenuationColor` property. This node property allows to overwrite the default
  15059. * and define the attenuation color with a node instead.
  15060. *
  15061. * If you don't want to overwrite the attenuation color but modify the existing
  15062. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  15063. *
  15064. * @type {Node<vec3>?}
  15065. * @default null
  15066. */
  15067. this.attenuationColorNode = null;
  15068. /**
  15069. * The dispersion of physical materials is by default inferred from the
  15070. * `dispersion` property. This node property allows to overwrite the default
  15071. * and define the dispersion with a node instead.
  15072. *
  15073. * If you don't want to overwrite the dispersion but modify the existing
  15074. * value instead, use {@link module:MaterialNode.materialDispersion}.
  15075. *
  15076. * @type {Node<float>?}
  15077. * @default null
  15078. */
  15079. this.dispersionNode = null;
  15080. /**
  15081. * The anisotropy of physical materials is by default inferred from the
  15082. * `anisotropy` property. This node property allows to overwrite the default
  15083. * and define the anisotropy with a node instead.
  15084. *
  15085. * If you don't want to overwrite the anisotropy but modify the existing
  15086. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  15087. *
  15088. * @type {Node<float>?}
  15089. * @default null
  15090. */
  15091. this.anisotropyNode = null;
  15092. this.setDefaultValues( _defaultValues$5 );
  15093. this.setValues( parameters );
  15094. }
  15095. /**
  15096. * Whether the lighting model should use clearcoat or not.
  15097. *
  15098. * @type {Boolean}
  15099. * @default true
  15100. */
  15101. get useClearcoat() {
  15102. return this.clearcoat > 0 || this.clearcoatNode !== null;
  15103. }
  15104. /**
  15105. * Whether the lighting model should use iridescence or not.
  15106. *
  15107. * @type {Boolean}
  15108. * @default true
  15109. */
  15110. get useIridescence() {
  15111. return this.iridescence > 0 || this.iridescenceNode !== null;
  15112. }
  15113. /**
  15114. * Whether the lighting model should use sheen or not.
  15115. *
  15116. * @type {Boolean}
  15117. * @default true
  15118. */
  15119. get useSheen() {
  15120. return this.sheen > 0 || this.sheenNode !== null;
  15121. }
  15122. /**
  15123. * Whether the lighting model should use anisotropy or not.
  15124. *
  15125. * @type {Boolean}
  15126. * @default true
  15127. */
  15128. get useAnisotropy() {
  15129. return this.anisotropy > 0 || this.anisotropyNode !== null;
  15130. }
  15131. /**
  15132. * Whether the lighting model should use transmission or not.
  15133. *
  15134. * @type {Boolean}
  15135. * @default true
  15136. */
  15137. get useTransmission() {
  15138. return this.transmission > 0 || this.transmissionNode !== null;
  15139. }
  15140. /**
  15141. * Whether the lighting model should use dispersion or not.
  15142. *
  15143. * @type {Boolean}
  15144. * @default true
  15145. */
  15146. get useDispersion() {
  15147. return this.dispersion > 0 || this.dispersionNode !== null;
  15148. }
  15149. /**
  15150. * Setups the specular related node variables.
  15151. */
  15152. setupSpecular() {
  15153. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  15154. ior.assign( iorNode );
  15155. 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 ) );
  15156. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  15157. }
  15158. /**
  15159. * Setups the lighting model.
  15160. *
  15161. * @return {PhysicalLightingModel} The lighting model.
  15162. */
  15163. setupLightingModel( /*builder*/ ) {
  15164. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  15165. }
  15166. /**
  15167. * Setups the physical specific node variables.
  15168. *
  15169. * @param {NodeBuilder} builder - The current node builder.
  15170. */
  15171. setupVariants( builder ) {
  15172. super.setupVariants( builder );
  15173. // CLEARCOAT
  15174. if ( this.useClearcoat ) {
  15175. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  15176. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  15177. clearcoat.assign( clearcoatNode );
  15178. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  15179. }
  15180. // SHEEN
  15181. if ( this.useSheen ) {
  15182. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  15183. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  15184. sheen.assign( sheenNode );
  15185. sheenRoughness.assign( sheenRoughnessNode );
  15186. }
  15187. // IRIDESCENCE
  15188. if ( this.useIridescence ) {
  15189. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  15190. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  15191. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  15192. iridescence.assign( iridescenceNode );
  15193. iridescenceIOR.assign( iridescenceIORNode );
  15194. iridescenceThickness.assign( iridescenceThicknessNode );
  15195. }
  15196. // ANISOTROPY
  15197. if ( this.useAnisotropy ) {
  15198. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  15199. anisotropy.assign( anisotropyV.length() );
  15200. If( anisotropy.equal( 0.0 ), () => {
  15201. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  15202. } ).Else( () => {
  15203. anisotropyV.divAssign( vec2( anisotropy ) );
  15204. anisotropy.assign( anisotropy.saturate() );
  15205. } );
  15206. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  15207. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  15208. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  15209. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  15210. }
  15211. // TRANSMISSION
  15212. if ( this.useTransmission ) {
  15213. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  15214. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  15215. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  15216. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  15217. transmission.assign( transmissionNode );
  15218. thickness.assign( thicknessNode );
  15219. attenuationDistance.assign( attenuationDistanceNode );
  15220. attenuationColor.assign( attenuationColorNode );
  15221. if ( this.useDispersion ) {
  15222. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  15223. dispersion.assign( dispersionNode );
  15224. }
  15225. }
  15226. }
  15227. /**
  15228. * Setups the clearcoat normal node.
  15229. *
  15230. * @return {Node<vec3>} The clearcoat normal.
  15231. */
  15232. setupClearcoatNormal() {
  15233. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  15234. }
  15235. setup( builder ) {
  15236. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15237. super.setup( builder );
  15238. }
  15239. copy( source ) {
  15240. this.clearcoatNode = source.clearcoatNode;
  15241. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15242. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15243. this.sheenNode = source.sheenNode;
  15244. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15245. this.iridescenceNode = source.iridescenceNode;
  15246. this.iridescenceIORNode = source.iridescenceIORNode;
  15247. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15248. this.specularIntensityNode = source.specularIntensityNode;
  15249. this.specularColorNode = source.specularColorNode;
  15250. this.transmissionNode = source.transmissionNode;
  15251. this.thicknessNode = source.thicknessNode;
  15252. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15253. this.attenuationColorNode = source.attenuationColorNode;
  15254. this.dispersionNode = source.dispersionNode;
  15255. this.anisotropyNode = source.anisotropyNode;
  15256. return super.copy( source );
  15257. }
  15258. }
  15259. /** @module MeshSSSNodeMaterial **/
  15260. /**
  15261. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15262. *
  15263. * @augments PhysicalLightingModel
  15264. */
  15265. class SSSLightingModel extends PhysicalLightingModel {
  15266. /**
  15267. * Constructs a new physical lighting model.
  15268. *
  15269. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15270. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15271. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15272. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15273. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15274. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15275. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15276. */
  15277. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15278. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15279. /**
  15280. * Whether the lighting model should use SSS or not.
  15281. *
  15282. * @type {Boolean}
  15283. * @default false
  15284. */
  15285. this.useSSS = sss;
  15286. }
  15287. /**
  15288. * Extends the default implementation with a SSS term.
  15289. *
  15290. * 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/}
  15291. *
  15292. * @param {Object} input - The input data.
  15293. * @param {StackNode} stack - The current stack.
  15294. * @param {NodeBuilder} builder - The current node builder.
  15295. */
  15296. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15297. if ( this.useSSS === true ) {
  15298. const material = builder.material;
  15299. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15300. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15301. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15302. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15303. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15304. }
  15305. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15306. }
  15307. }
  15308. /**
  15309. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15310. * that implements a Subsurface scattering (SSS) term.
  15311. *
  15312. * @augments MeshPhysicalNodeMaterial
  15313. */
  15314. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15315. static get type() {
  15316. return 'MeshSSSNodeMaterial';
  15317. }
  15318. /**
  15319. * Constructs a new mesh SSS node material.
  15320. *
  15321. * @param {Object?} parameters - The configuration parameter.
  15322. */
  15323. constructor( parameters ) {
  15324. super( parameters );
  15325. /**
  15326. * Represents the thickness color.
  15327. *
  15328. * @type {Node<vec3>?}
  15329. * @default null
  15330. */
  15331. this.thicknessColorNode = null;
  15332. /**
  15333. * Represents the distortion factor.
  15334. *
  15335. * @type {Node<float>?}
  15336. */
  15337. this.thicknessDistortionNode = float( 0.1 );
  15338. /**
  15339. * Represents the thickness ambient factor.
  15340. *
  15341. * @type {Node<float>?}
  15342. */
  15343. this.thicknessAmbientNode = float( 0.0 );
  15344. /**
  15345. * Represents the thickness attenuation.
  15346. *
  15347. * @type {Node<float>?}
  15348. */
  15349. this.thicknessAttenuationNode = float( .1 );
  15350. /**
  15351. * Represents the thickness power.
  15352. *
  15353. * @type {Node<float>?}
  15354. */
  15355. this.thicknessPowerNode = float( 2.0 );
  15356. /**
  15357. * Represents the thickness scale.
  15358. *
  15359. * @type {Node<float>?}
  15360. */
  15361. this.thicknessScaleNode = float( 10.0 );
  15362. }
  15363. /**
  15364. * Whether the lighting model should use SSS or not.
  15365. *
  15366. * @type {Boolean}
  15367. * @default true
  15368. */
  15369. get useSSS() {
  15370. return this.thicknessColorNode !== null;
  15371. }
  15372. /**
  15373. * Setups the lighting model.
  15374. *
  15375. * @return {SSSLightingModel} The lighting model.
  15376. */
  15377. setupLightingModel( /*builder*/ ) {
  15378. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15379. }
  15380. copy( source ) {
  15381. this.thicknessColorNode = source.thicknessColorNode;
  15382. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15383. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15384. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15385. this.thicknessPowerNode = source.thicknessPowerNode;
  15386. this.thicknessScaleNode = source.thicknessScaleNode;
  15387. return super.copy( source );
  15388. }
  15389. }
  15390. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15391. // dotNL will be from -1.0 to 1.0
  15392. const dotNL = normal.dot( lightDirection );
  15393. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15394. if ( builder.material.gradientMap ) {
  15395. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15396. return vec3( gradientMap.r );
  15397. } else {
  15398. const fw = coord.fwidth().mul( 0.5 );
  15399. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15400. }
  15401. } );
  15402. /**
  15403. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15404. *
  15405. * @augments LightingModel
  15406. */
  15407. class ToonLightingModel extends LightingModel {
  15408. /**
  15409. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15410. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15411. *
  15412. * @param {Object} input - The input data.
  15413. * @param {StackNode} stack - The current stack.
  15414. * @param {NodeBuilder} builder - The current node builder.
  15415. */
  15416. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15417. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15418. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15419. }
  15420. /**
  15421. * Implements the indirect lighting.
  15422. *
  15423. * @param {ContextNode} input - The current node context.
  15424. * @param {StackNode} stack - The current stack.
  15425. * @param {NodeBuilder} builder - The current node builder.
  15426. */
  15427. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15428. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15429. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15430. }
  15431. }
  15432. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15433. /**
  15434. * Node material version of `MeshToonMaterial`.
  15435. *
  15436. * @augments NodeMaterial
  15437. */
  15438. class MeshToonNodeMaterial extends NodeMaterial {
  15439. static get type() {
  15440. return 'MeshToonNodeMaterial';
  15441. }
  15442. /**
  15443. * Constructs a new mesh toon node material.
  15444. *
  15445. * @param {Object?} parameters - The configuration parameter.
  15446. */
  15447. constructor( parameters ) {
  15448. super();
  15449. /**
  15450. * This flag can be used for type testing.
  15451. *
  15452. * @type {Boolean}
  15453. * @readonly
  15454. * @default true
  15455. */
  15456. this.isMeshToonNodeMaterial = true;
  15457. /**
  15458. * Set to `true` because toon materials react on lights.
  15459. *
  15460. * @type {Boolean}
  15461. * @default true
  15462. */
  15463. this.lights = true;
  15464. this.setDefaultValues( _defaultValues$4 );
  15465. this.setValues( parameters );
  15466. }
  15467. /**
  15468. * Setups the lighting model.
  15469. *
  15470. * @return {ToonLightingModel} The lighting model.
  15471. */
  15472. setupLightingModel( /*builder*/ ) {
  15473. return new ToonLightingModel();
  15474. }
  15475. }
  15476. /** @module MatcapUVNode **/
  15477. /**
  15478. * Can be used to compute texture coordinates for projecting a
  15479. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15480. *
  15481. * @augments TempNode
  15482. */
  15483. class MatcapUVNode extends TempNode {
  15484. static get type() {
  15485. return 'MatcapUVNode';
  15486. }
  15487. /**
  15488. * Constructs a new matcap uv node.
  15489. */
  15490. constructor() {
  15491. super( 'vec2' );
  15492. }
  15493. setup() {
  15494. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15495. const y = positionViewDirection.cross( x );
  15496. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15497. }
  15498. }
  15499. /**
  15500. * TSL function for creating a matcap uv node.
  15501. *
  15502. * @function
  15503. * @returns {MatcapUVNode}
  15504. */
  15505. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15506. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15507. /**
  15508. * Node material version of `MeshMatcapMaterial`.
  15509. *
  15510. * @augments NodeMaterial
  15511. */
  15512. class MeshMatcapNodeMaterial extends NodeMaterial {
  15513. static get type() {
  15514. return 'MeshMatcapNodeMaterial';
  15515. }
  15516. /**
  15517. * Constructs a new mesh normal node material.
  15518. *
  15519. * @param {Object?} parameters - The configuration parameter.
  15520. */
  15521. constructor( parameters ) {
  15522. super();
  15523. /**
  15524. * This flag can be used for type testing.
  15525. *
  15526. * @type {Boolean}
  15527. * @readonly
  15528. * @default true
  15529. */
  15530. this.isMeshMatcapNodeMaterial = true;
  15531. this.setDefaultValues( _defaultValues$3 );
  15532. this.setValues( parameters );
  15533. }
  15534. /**
  15535. * Setups the matcap specific node variables.
  15536. *
  15537. * @param {NodeBuilder} builder - The current node builder.
  15538. */
  15539. setupVariants( builder ) {
  15540. const uv = matcapUV;
  15541. let matcapColor;
  15542. if ( builder.material.matcap ) {
  15543. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15544. } else {
  15545. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15546. }
  15547. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15548. }
  15549. }
  15550. /** @module RotateNode **/
  15551. /**
  15552. * Applies a rotation to the given position node.
  15553. *
  15554. * @augments TempNode
  15555. */
  15556. class RotateNode extends TempNode {
  15557. static get type() {
  15558. return 'RotateNode';
  15559. }
  15560. /**
  15561. * Constructs a new rotate node.
  15562. *
  15563. * @param {Node} positionNode - The position node.
  15564. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15565. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15566. */
  15567. constructor( positionNode, rotationNode ) {
  15568. super();
  15569. /**
  15570. * The position node.
  15571. *
  15572. * @type {Node}
  15573. */
  15574. this.positionNode = positionNode;
  15575. /**
  15576. * Represents the rotation that is applied to the position node.
  15577. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15578. *
  15579. * @type {Node}
  15580. */
  15581. this.rotationNode = rotationNode;
  15582. }
  15583. /**
  15584. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15585. *
  15586. * @param {NodeBuilder} builder - The current node builder.
  15587. * @return {String} The node's type.
  15588. */
  15589. getNodeType( builder ) {
  15590. return this.positionNode.getNodeType( builder );
  15591. }
  15592. setup( builder ) {
  15593. const { rotationNode, positionNode } = this;
  15594. const nodeType = this.getNodeType( builder );
  15595. if ( nodeType === 'vec2' ) {
  15596. const cosAngle = rotationNode.cos();
  15597. const sinAngle = rotationNode.sin();
  15598. const rotationMatrix = mat2(
  15599. cosAngle, sinAngle,
  15600. sinAngle.negate(), cosAngle
  15601. );
  15602. return rotationMatrix.mul( positionNode );
  15603. } else {
  15604. const rotation = rotationNode;
  15605. 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 ) );
  15606. 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 ) );
  15607. 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 ) );
  15608. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15609. }
  15610. }
  15611. }
  15612. /**
  15613. * TSL function for creating a rotate node.
  15614. *
  15615. * @function
  15616. * @param {Node} positionNode - The position node.
  15617. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15618. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15619. * @returns {RotateNode}
  15620. */
  15621. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15622. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  15623. /**
  15624. * Node material version of `SpriteMaterial`.
  15625. *
  15626. * @augments NodeMaterial
  15627. */
  15628. class SpriteNodeMaterial extends NodeMaterial {
  15629. static get type() {
  15630. return 'SpriteNodeMaterial';
  15631. }
  15632. /**
  15633. * Constructs a new sprite node material.
  15634. *
  15635. * @param {Object?} parameters - The configuration parameter.
  15636. */
  15637. constructor( parameters ) {
  15638. super();
  15639. /**
  15640. * This flag can be used for type testing.
  15641. *
  15642. * @type {Boolean}
  15643. * @readonly
  15644. * @default true
  15645. */
  15646. this.isSpriteNodeMaterial = true;
  15647. this._useSizeAttenuation = true;
  15648. /**
  15649. * This property makes it possible to define the position of the sprite with a
  15650. * node. That can be useful when the material is used with instanced rendering
  15651. * and node data are defined with an instanced attribute node:
  15652. * ```js
  15653. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15654. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15655. * ```
  15656. * Another possibility is to compute the instanced data with a compute shader:
  15657. * ```js
  15658. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15659. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15660. * ```
  15661. *
  15662. * @type {Node<vec2>?}
  15663. * @default null
  15664. */
  15665. this.positionNode = null;
  15666. /**
  15667. * The rotation of sprite materials is by default inferred from the `rotation`,
  15668. * property. This node property allows to overwrite the default and define
  15669. * the rotation with a node instead.
  15670. *
  15671. * If you don't want to overwrite the rotation but modify the existing
  15672. * value instead, use {@link module:MaterialNode.materialRotation}.
  15673. *
  15674. * @type {Node<float>?}
  15675. * @default null
  15676. */
  15677. this.rotationNode = null;
  15678. /**
  15679. * This node property provides an additional way to scale sprites next to
  15680. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15681. * is multiplied with the scale value of this node in the vertex shader.
  15682. *
  15683. * @type {Node<vec2>?}
  15684. * @default null
  15685. */
  15686. this.scaleNode = null;
  15687. this.setDefaultValues( _defaultValues$2 );
  15688. this.setValues( parameters );
  15689. }
  15690. /**
  15691. * Setups the position node in view space. This method implements
  15692. * the sprite specific vertex shader.
  15693. *
  15694. * @param {NodeBuilder} builder - The current node builder.
  15695. * @return {Node<vec3>} The position in view space.
  15696. */
  15697. setupPositionView( builder ) {
  15698. const { object, camera } = builder;
  15699. const sizeAttenuation = this.sizeAttenuation;
  15700. const { positionNode, rotationNode, scaleNode } = this;
  15701. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15702. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15703. if ( scaleNode !== null ) {
  15704. scale = scale.mul( float( scaleNode ) );
  15705. }
  15706. if ( sizeAttenuation === false ) {
  15707. if ( camera.isPerspectiveCamera ) {
  15708. scale = scale.mul( mvPosition.z.negate() );
  15709. } else {
  15710. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15711. scale = scale.mul( orthoScale.mul( 2 ) );
  15712. }
  15713. }
  15714. let alignedPosition = positionGeometry.xy;
  15715. if ( object.center && object.center.isVector2 === true ) {
  15716. const center = reference$1( 'center', 'vec2', object );
  15717. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15718. }
  15719. alignedPosition = alignedPosition.mul( scale );
  15720. const rotation = float( rotationNode || materialRotation );
  15721. const rotatedPosition = rotate( alignedPosition, rotation );
  15722. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15723. }
  15724. copy( source ) {
  15725. this.positionNode = source.positionNode;
  15726. this.rotationNode = source.rotationNode;
  15727. this.scaleNode = source.scaleNode;
  15728. return super.copy( source );
  15729. }
  15730. /**
  15731. * Whether to use size attenuation or not.
  15732. *
  15733. * @type {Boolean}
  15734. * @default true
  15735. */
  15736. get sizeAttenuation() {
  15737. return this._useSizeAttenuation;
  15738. }
  15739. set sizeAttenuation( value ) {
  15740. if ( this._useSizeAttenuation !== value ) {
  15741. this._useSizeAttenuation = value;
  15742. this.needsUpdate = true;
  15743. }
  15744. }
  15745. }
  15746. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  15747. /**
  15748. * Node material version of `PointsMaterial`.
  15749. *
  15750. * @augments NodeMaterial
  15751. */
  15752. class PointsNodeMaterial extends SpriteNodeMaterial {
  15753. static get type() {
  15754. return 'PointsNodeMaterial';
  15755. }
  15756. /**
  15757. * Constructs a new points node material.
  15758. *
  15759. * @param {Object?} parameters - The configuration parameter.
  15760. */
  15761. constructor( parameters ) {
  15762. super();
  15763. /**
  15764. * This node property provides an additional way to set the point size.
  15765. *
  15766. * @type {Node<vec2>?}
  15767. * @default null
  15768. */
  15769. this.sizeNode = null;
  15770. /**
  15771. * This flag can be used for type testing.
  15772. *
  15773. * @type {Boolean}
  15774. * @readonly
  15775. * @default true
  15776. */
  15777. this.isPointsNodeMaterial = true;
  15778. this.setDefaultValues( _defaultValues$1 );
  15779. this.setValues( parameters );
  15780. }
  15781. setupPositionView() {
  15782. const { positionNode } = this;
  15783. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  15784. }
  15785. setupVertex( builder ) {
  15786. const mvp = super.setupVertex( builder );
  15787. // skip further processing if the material is not a node material
  15788. if ( builder.material.isNodeMaterial !== true ) {
  15789. return mvp;
  15790. }
  15791. // ndc space
  15792. const { rotationNode, scaleNode, sizeNode } = this;
  15793. const alignedPosition = positionGeometry.xy.toVar();
  15794. const aspect = viewport.z.div( viewport.w );
  15795. // rotation
  15796. if ( rotationNode && rotationNode.isNode ) {
  15797. const rotation = float( rotationNode );
  15798. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  15799. }
  15800. // point size
  15801. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  15802. if ( this.sizeAttenuation === true ) {
  15803. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  15804. }
  15805. // scale
  15806. if ( scaleNode && scaleNode.isNode ) {
  15807. pointSize = pointSize.mul( vec2( scaleNode ) );
  15808. }
  15809. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  15810. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  15811. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  15812. // back to clip space
  15813. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  15814. //clipPos.xy += offset;
  15815. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  15816. return mvp;
  15817. }
  15818. /**
  15819. * Whether alpha to coverage should be used or not.
  15820. *
  15821. * @type {Boolean}
  15822. * @default true
  15823. */
  15824. get alphaToCoverage() {
  15825. return this._useAlphaToCoverage;
  15826. }
  15827. set alphaToCoverage( value ) {
  15828. if ( this._useAlphaToCoverage !== value ) {
  15829. this._useAlphaToCoverage = value;
  15830. this.needsUpdate = true;
  15831. }
  15832. }
  15833. }
  15834. /**
  15835. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15836. *
  15837. * @augments LightingModel
  15838. */
  15839. class ShadowMaskModel extends LightingModel {
  15840. /**
  15841. * Constructs a new shadow mask model.
  15842. */
  15843. constructor() {
  15844. super();
  15845. /**
  15846. * The shadow mask node.
  15847. *
  15848. * @type {Node}
  15849. */
  15850. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15851. }
  15852. /**
  15853. * Only used to save the shadow mask.
  15854. *
  15855. * @param {Object} input - The input data.
  15856. */
  15857. direct( { shadowMask } ) {
  15858. this.shadowNode.mulAssign( shadowMask );
  15859. }
  15860. /**
  15861. * Uses the shadow mask to produce the final color.
  15862. *
  15863. * @param {ContextNode} context - The current node context.
  15864. */
  15865. finish( context ) {
  15866. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15867. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15868. }
  15869. }
  15870. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15871. /**
  15872. * Node material version of `ShadowMaterial`.
  15873. *
  15874. * @augments NodeMaterial
  15875. */
  15876. class ShadowNodeMaterial extends NodeMaterial {
  15877. static get type() {
  15878. return 'ShadowNodeMaterial';
  15879. }
  15880. /**
  15881. * Constructs a new shadow node material.
  15882. *
  15883. * @param {Object?} parameters - The configuration parameter.
  15884. */
  15885. constructor( parameters ) {
  15886. super();
  15887. /**
  15888. * This flag can be used for type testing.
  15889. *
  15890. * @type {Boolean}
  15891. * @readonly
  15892. * @default true
  15893. */
  15894. this.isShadowNodeMaterial = true;
  15895. /**
  15896. * Set to `true` because so it's possible to implement
  15897. * the shadow mask effect.
  15898. *
  15899. * @type {Boolean}
  15900. * @default true
  15901. */
  15902. this.lights = true;
  15903. this.setDefaultValues( _defaultValues );
  15904. this.setValues( parameters );
  15905. }
  15906. /**
  15907. * Setups the lighting model.
  15908. *
  15909. * @return {ShadowMaskModel} The lighting model.
  15910. */
  15911. setupLightingModel( /*builder*/ ) {
  15912. return new ShadowMaskModel();
  15913. }
  15914. }
  15915. /** @module Texture3DNode **/
  15916. const normal = Fn( ( { texture, uv } ) => {
  15917. const epsilon = 0.0001;
  15918. const ret = vec3().toVar();
  15919. If( uv.x.lessThan( epsilon ), () => {
  15920. ret.assign( vec3( 1, 0, 0 ) );
  15921. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15922. ret.assign( vec3( 0, 1, 0 ) );
  15923. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15924. ret.assign( vec3( 0, 0, 1 ) );
  15925. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15926. ret.assign( vec3( - 1, 0, 0 ) );
  15927. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15928. ret.assign( vec3( 0, - 1, 0 ) );
  15929. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15930. ret.assign( vec3( 0, 0, - 1 ) );
  15931. } ).Else( () => {
  15932. const step = 0.01;
  15933. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  15934. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  15935. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  15936. ret.assign( vec3( x, y, z ) );
  15937. } );
  15938. return ret.normalize();
  15939. } );
  15940. /**
  15941. * This type of uniform node represents a 3D texture.
  15942. *
  15943. * @augments module:TextureNode~TextureNode
  15944. */
  15945. class Texture3DNode extends TextureNode {
  15946. static get type() {
  15947. return 'Texture3DNode';
  15948. }
  15949. /**
  15950. * Constructs a new 3D texture node.
  15951. *
  15952. * @param {Data3DTexture} value - The 3D texture.
  15953. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15954. * @param {Node<int>?} [levelNode=null] - The level node.
  15955. */
  15956. constructor( value, uvNode = null, levelNode = null ) {
  15957. super( value, uvNode, levelNode );
  15958. /**
  15959. * This flag can be used for type testing.
  15960. *
  15961. * @type {Boolean}
  15962. * @readonly
  15963. * @default true
  15964. */
  15965. this.isTexture3DNode = true;
  15966. }
  15967. /**
  15968. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15969. *
  15970. * @param {NodeBuilder} builder - The current node builder.
  15971. * @return {String} The input type.
  15972. */
  15973. getInputType( /*builder*/ ) {
  15974. return 'texture3D';
  15975. }
  15976. /**
  15977. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15978. * uv node.
  15979. *
  15980. * @return {Node<vec3>} The default uv node.
  15981. */
  15982. getDefaultUV() {
  15983. return vec3( 0.5, 0.5, 0.5 );
  15984. }
  15985. /**
  15986. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15987. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15988. *
  15989. * @param {Boolean} value - The update toggle.
  15990. */
  15991. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15992. /**
  15993. * Overwrites the default implementation to return the unmodified uv node.
  15994. *
  15995. * @param {NodeBuilder} builder - The current node builder.
  15996. * @param {Node} uvNode - The uv node to setup.
  15997. * @return {Node} The unmodified uv node.
  15998. */
  15999. setupUV( builder, uvNode ) {
  16000. const texture = this.value;
  16001. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  16002. if ( this.sampler ) {
  16003. uvNode = uvNode.flipY();
  16004. } else {
  16005. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  16006. }
  16007. }
  16008. return uvNode;
  16009. }
  16010. /**
  16011. * Generates the uv code snippet.
  16012. *
  16013. * @param {NodeBuilder} builder - The current node builder.
  16014. * @param {Node} uvNode - The uv node to generate code for.
  16015. * @return {String} The generated code snippet.
  16016. */
  16017. generateUV( builder, uvNode ) {
  16018. return uvNode.build( builder, 'vec3' );
  16019. }
  16020. /**
  16021. * TODO.
  16022. *
  16023. * @param {Node<vec3>} uvNode - The uv node .
  16024. * @return {Node<vec3>} TODO.
  16025. */
  16026. normal( uvNode ) {
  16027. return normal( { texture: this, uv: uvNode } );
  16028. }
  16029. }
  16030. /**
  16031. * TSL function for creating a 3D texture node.
  16032. *
  16033. * @function
  16034. * @param {Data3DTexture} value - The 3D texture.
  16035. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  16036. * @param {Node<int>?} [levelNode=null] - The level node.
  16037. * @returns {Texture3DNode}
  16038. */
  16039. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  16040. /** @module VolumeNodeMaterial **/
  16041. /**
  16042. * Node material intended for volume rendering. The volumetric data are
  16043. * defined with an instance of {@link Data3DTexture}.
  16044. *
  16045. * @augments NodeMaterial
  16046. */
  16047. class VolumeNodeMaterial extends NodeMaterial {
  16048. static get type() {
  16049. return 'VolumeNodeMaterial';
  16050. }
  16051. /**
  16052. * Constructs a new volume node material.
  16053. *
  16054. * @param {Object?} parameters - The configuration parameter.
  16055. */
  16056. constructor( parameters ) {
  16057. super();
  16058. /**
  16059. * This flag can be used for type testing.
  16060. *
  16061. * @type {Boolean}
  16062. * @readonly
  16063. * @default true
  16064. */
  16065. this.isVolumeNodeMaterial = true;
  16066. /**
  16067. * The base color of the volume.
  16068. *
  16069. * @type {Color}
  16070. * @default 100
  16071. */
  16072. this.base = new Color( 0xffffff );
  16073. /**
  16074. * A 3D data texture holding the volumetric data.
  16075. *
  16076. * @type {Data3DTexture?}
  16077. * @default null
  16078. */
  16079. this.map = null;
  16080. /**
  16081. * This number of samples for each ray that hits the mesh's surface
  16082. * and travels through the volume.
  16083. *
  16084. * @type {Number}
  16085. * @default 100
  16086. */
  16087. this.steps = 100;
  16088. /**
  16089. * Callback for {@link VolumeNodeMaterial#testNode}.
  16090. *
  16091. * @callback testNodeCallback
  16092. * @param {Data3DTexture<float>} map - The 3D texture.
  16093. * @param {Node<float>} mapValue - The sampled value inside the volume.
  16094. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  16095. * @param {Node<vec4>} finalColor - The final color.
  16096. */
  16097. /**
  16098. * The volume rendering of this material works by shooting rays
  16099. * from the camera position through each fragment of the mesh's
  16100. * surface and sample the inner volume in a raymarching fashion
  16101. * multiple times.
  16102. *
  16103. * This node can be used to assign a callback function of type `Fn`
  16104. * that will be executed per sample. The callback receives the
  16105. * texture, the sampled texture value as well as position on the surface
  16106. * where the rays enters the volume. The last parameter is a color
  16107. * that allows the callback to determine the final color.
  16108. *
  16109. * @type {testNodeCallback?}
  16110. * @default null
  16111. */
  16112. this.testNode = null;
  16113. this.setValues( parameters );
  16114. }
  16115. /**
  16116. * Setups the vertex and fragment stage of this node material.
  16117. *
  16118. * @param {NodeBuilder} builder - The current node builder.
  16119. */
  16120. setup( builder ) {
  16121. const map = texture3D( this.map, null, 0 );
  16122. const hitBox = Fn( ( { orig, dir } ) => {
  16123. const box_min = vec3( - 0.5 );
  16124. const box_max = vec3( 0.5 );
  16125. const inv_dir = dir.reciprocal();
  16126. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  16127. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  16128. const tmin = min$1( tmin_tmp, tmax_tmp );
  16129. const tmax = max$1( tmin_tmp, tmax_tmp );
  16130. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  16131. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  16132. return vec2( t0, t1 );
  16133. } );
  16134. this.fragmentNode = Fn( () => {
  16135. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  16136. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  16137. const rayDir = vDirection.normalize();
  16138. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  16139. bounds.x.greaterThan( bounds.y ).discard();
  16140. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  16141. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  16142. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  16143. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  16144. delta.divAssign( materialReference( 'steps', 'float' ) );
  16145. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  16146. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  16147. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  16148. if ( this.testNode !== null ) {
  16149. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  16150. } else {
  16151. // default to show surface of mesh
  16152. ac.a.assign( 1 );
  16153. Break();
  16154. }
  16155. p.addAssign( rayDir.mul( delta ) );
  16156. } );
  16157. ac.a.equal( 0 ).discard();
  16158. return vec4( ac );
  16159. } )();
  16160. super.setup( builder );
  16161. }
  16162. }
  16163. /**
  16164. * This module manages the internal animation loop of the renderer.
  16165. *
  16166. * @private
  16167. */
  16168. class Animation {
  16169. /**
  16170. * Constructs a new animation loop management component.
  16171. *
  16172. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16173. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16174. */
  16175. constructor( nodes, info ) {
  16176. /**
  16177. * Renderer component for managing nodes related logic.
  16178. *
  16179. * @type {Nodes}
  16180. */
  16181. this.nodes = nodes;
  16182. /**
  16183. * Renderer component for managing metrics and monitoring data.
  16184. *
  16185. * @type {Info}
  16186. */
  16187. this.info = info;
  16188. /**
  16189. * A reference to the context from `requestAnimationFrame()` can
  16190. * be called (usually `window`).
  16191. *
  16192. * @type {Window|XRSession}
  16193. */
  16194. this._context = self;
  16195. /**
  16196. * The user-defined animation loop.
  16197. *
  16198. * @type {Function?}
  16199. * @default null
  16200. */
  16201. this._animationLoop = null;
  16202. /**
  16203. * The requestId which is returned from the `requestAnimationFrame()` call.
  16204. * Can be used to cancel the stop the animation loop.
  16205. *
  16206. * @type {Number?}
  16207. * @default null
  16208. */
  16209. this._requestId = null;
  16210. }
  16211. /**
  16212. * Starts the internal animation loop.
  16213. */
  16214. start() {
  16215. const update = ( time, frame ) => {
  16216. this._requestId = this._context.requestAnimationFrame( update );
  16217. if ( this.info.autoReset === true ) this.info.reset();
  16218. this.nodes.nodeFrame.update();
  16219. this.info.frame = this.nodes.nodeFrame.frameId;
  16220. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  16221. };
  16222. update();
  16223. }
  16224. /**
  16225. * Stops the internal animation loop.
  16226. */
  16227. stop() {
  16228. this._context.cancelAnimationFrame( this._requestId );
  16229. this._requestId = null;
  16230. }
  16231. /**
  16232. * Returns the user-level animation loop.
  16233. *
  16234. * @return {Function} The animation loop.
  16235. */
  16236. getAnimationLoop() {
  16237. return this._animationLoop;
  16238. }
  16239. /**
  16240. * Defines the user-level animation loop.
  16241. *
  16242. * @param {Function} callback - The animation loop.
  16243. */
  16244. setAnimationLoop( callback ) {
  16245. this._animationLoop = callback;
  16246. }
  16247. /**
  16248. * Returns the animation context.
  16249. *
  16250. * @return {Window|XRSession} The animation context.
  16251. */
  16252. getContext() {
  16253. return this._context;
  16254. }
  16255. /**
  16256. * Defines the context in which `requestAnimationFrame()` is executed.
  16257. *
  16258. * @param {Window|XRSession} context - The context to set.
  16259. */
  16260. setContext( context ) {
  16261. this._context = context;
  16262. }
  16263. /**
  16264. * Frees all internal resources and stops the animation loop.
  16265. */
  16266. dispose() {
  16267. this.stop();
  16268. }
  16269. }
  16270. /**
  16271. * Data structure for the renderer. It allows defining values
  16272. * with chained, hierarchical keys. Keys are meant to be
  16273. * objects since the module internally works with Weak Maps
  16274. * for performance reasons.
  16275. *
  16276. * @private
  16277. */
  16278. class ChainMap {
  16279. /**
  16280. * Constructs a new Chain Map.
  16281. */
  16282. constructor() {
  16283. /**
  16284. * The root Weak Map.
  16285. *
  16286. * @type {WeakMap}
  16287. */
  16288. this.weakMap = new WeakMap();
  16289. }
  16290. /**
  16291. * Returns the value for the given array of keys.
  16292. *
  16293. * @param {Array<Object>} keys - List of keys.
  16294. * @return {Any} The value. Returns `undefined` if no value was found.
  16295. */
  16296. get( keys ) {
  16297. let map = this.weakMap;
  16298. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16299. map = map.get( keys[ i ] );
  16300. if ( map === undefined ) return undefined;
  16301. }
  16302. return map.get( keys[ keys.length - 1 ] );
  16303. }
  16304. /**
  16305. * Sets the value for the given keys.
  16306. *
  16307. * @param {Array<Object>} keys - List of keys.
  16308. * @param {Any} value - The value to set.
  16309. * @return {ChainMap} A reference to this Chain Map.
  16310. */
  16311. set( keys, value ) {
  16312. let map = this.weakMap;
  16313. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16314. const key = keys[ i ];
  16315. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16316. map = map.get( key );
  16317. }
  16318. map.set( keys[ keys.length - 1 ], value );
  16319. return this;
  16320. }
  16321. /**
  16322. * Deletes a value for the given keys.
  16323. *
  16324. * @param {Array<Object>} keys - The keys.
  16325. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16326. */
  16327. delete( keys ) {
  16328. let map = this.weakMap;
  16329. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16330. map = map.get( keys[ i ] );
  16331. if ( map === undefined ) return false;
  16332. }
  16333. return map.delete( keys[ keys.length - 1 ] );
  16334. }
  16335. }
  16336. let _id$9 = 0;
  16337. function getKeys( obj ) {
  16338. const keys = Object.keys( obj );
  16339. let proto = Object.getPrototypeOf( obj );
  16340. while ( proto ) {
  16341. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16342. for ( const key in descriptors ) {
  16343. if ( descriptors[ key ] !== undefined ) {
  16344. const descriptor = descriptors[ key ];
  16345. if ( descriptor && typeof descriptor.get === 'function' ) {
  16346. keys.push( key );
  16347. }
  16348. }
  16349. }
  16350. proto = Object.getPrototypeOf( proto );
  16351. }
  16352. return keys;
  16353. }
  16354. /**
  16355. * A render object is the renderer's representation of single entity that gets drawn
  16356. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16357. * scene since render objects also depend from the used material, the current render context
  16358. * and the current scene's lighting.
  16359. *
  16360. * In general, the basic process of the renderer is:
  16361. *
  16362. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16363. * - Process the render lists by calling one or more render commands for each render item.
  16364. * - For each render command, request a render object and perform the draw.
  16365. *
  16366. * The module provides an interface to get data required for the draw command like the actual
  16367. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16368. * creating render objects should only be done when necessary.
  16369. *
  16370. * @private
  16371. */
  16372. class RenderObject {
  16373. /**
  16374. * Constructs a new render object.
  16375. *
  16376. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16377. * @param {Geometries} geometries - Renderer component for managing geometries.
  16378. * @param {Renderer} renderer - The renderer.
  16379. * @param {Object3D} object - The 3D object.
  16380. * @param {Material} material - The 3D object's material.
  16381. * @param {Scene} scene - The scene the 3D object belongs to.
  16382. * @param {Camera} camera - The camera the object should be rendered with.
  16383. * @param {LightsNode} lightsNode - The lights node.
  16384. * @param {RenderContext} renderContext - The render context.
  16385. * @param {ClippingContext} clippingContext - The clipping context.
  16386. */
  16387. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16388. this.id = _id$9 ++;
  16389. /**
  16390. * Renderer component for managing nodes related logic.
  16391. *
  16392. * @type {Nodes}
  16393. * @private
  16394. */
  16395. this._nodes = nodes;
  16396. /**
  16397. * Renderer component for managing geometries.
  16398. *
  16399. * @type {Geometries}
  16400. * @private
  16401. */
  16402. this._geometries = geometries;
  16403. /**
  16404. * The renderer.
  16405. *
  16406. * @type {Renderer}
  16407. */
  16408. this.renderer = renderer;
  16409. /**
  16410. * The 3D object.
  16411. *
  16412. * @type {Object3D}
  16413. */
  16414. this.object = object;
  16415. /**
  16416. * The 3D object's material.
  16417. *
  16418. * @type {Material}
  16419. */
  16420. this.material = material;
  16421. /**
  16422. * The scene the 3D object belongs to.
  16423. *
  16424. * @type {Scene}
  16425. */
  16426. this.scene = scene;
  16427. /**
  16428. * The camera the 3D object should be rendered with.
  16429. *
  16430. * @type {Camera}
  16431. */
  16432. this.camera = camera;
  16433. /**
  16434. * The lights node.
  16435. *
  16436. * @type {LightsNode}
  16437. */
  16438. this.lightsNode = lightsNode;
  16439. /**
  16440. * The render context.
  16441. *
  16442. * @type {RenderContext}
  16443. */
  16444. this.context = renderContext;
  16445. /**
  16446. * The 3D object's geometry.
  16447. *
  16448. * @type {BufferGeometry}
  16449. */
  16450. this.geometry = object.geometry;
  16451. /**
  16452. * The render object's version.
  16453. *
  16454. * @type {Number}
  16455. */
  16456. this.version = material.version;
  16457. /**
  16458. * The draw range of the geometry.
  16459. *
  16460. * @type {Object?}
  16461. * @default null
  16462. */
  16463. this.drawRange = null;
  16464. /**
  16465. * An array holding the buffer attributes
  16466. * of the render object. This entails attribute
  16467. * definitions on geometry and node level.
  16468. *
  16469. * @type {Array<BufferAttribute>?}
  16470. * @default null
  16471. */
  16472. this.attributes = null;
  16473. /**
  16474. * A reference to a render pipeline the render
  16475. * object is processed with.
  16476. *
  16477. * @type {RenderPipeline}
  16478. * @default null
  16479. */
  16480. this.pipeline = null;
  16481. /**
  16482. * Only relevant for objects using
  16483. * multiple materials. This represents a group entry
  16484. * from the respective `BufferGeometry`.
  16485. *
  16486. * @type {{start: Number, count: Number}?}
  16487. * @default null
  16488. */
  16489. this.group = null;
  16490. /**
  16491. * An array holding the vertex buffers which can
  16492. * be buffer attributes but also interleaved buffers.
  16493. *
  16494. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16495. * @default null
  16496. */
  16497. this.vertexBuffers = null;
  16498. /**
  16499. * The parameters for the draw command.
  16500. *
  16501. * @type {Object?}
  16502. * @default null
  16503. */
  16504. this.drawParams = null;
  16505. /**
  16506. * If this render object is used inside a render bundle,
  16507. * this property points to the respective bundle group.
  16508. *
  16509. * @type {BundleGroup?}
  16510. * @default null
  16511. */
  16512. this.bundle = null;
  16513. /**
  16514. * The clipping context.
  16515. *
  16516. * @type {ClippingContext}
  16517. */
  16518. this.clippingContext = clippingContext;
  16519. /**
  16520. * The clipping context's cache key.
  16521. *
  16522. * @type {String}
  16523. */
  16524. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16525. /**
  16526. * The initial node cache key.
  16527. *
  16528. * @type {Number}
  16529. */
  16530. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16531. /**
  16532. * The initial cache key.
  16533. *
  16534. * @type {Number}
  16535. */
  16536. this.initialCacheKey = this.getCacheKey();
  16537. /**
  16538. * The node builder state.
  16539. *
  16540. * @type {NodeBuilderState?}
  16541. * @private
  16542. * @default null
  16543. */
  16544. this._nodeBuilderState = null;
  16545. /**
  16546. * An array of bindings.
  16547. *
  16548. * @type {Array<BindGroup>?}
  16549. * @private
  16550. * @default null
  16551. */
  16552. this._bindings = null;
  16553. /**
  16554. * Reference to the node material observer.
  16555. *
  16556. * @type {NodeMaterialObserver?}
  16557. * @private
  16558. * @default null
  16559. */
  16560. this._monitor = null;
  16561. /**
  16562. * An event listener which is defined by `RenderObjects`. It performs
  16563. * clean up tasks when `dispose()` on this render object.
  16564. *
  16565. * @method
  16566. */
  16567. this.onDispose = null;
  16568. /**
  16569. * This flag can be used for type testing.
  16570. *
  16571. * @type {Boolean}
  16572. * @readonly
  16573. * @default true
  16574. */
  16575. this.isRenderObject = true;
  16576. /**
  16577. * An event listener which is executed when `dispose()` is called on
  16578. * the render object's material.
  16579. *
  16580. * @method
  16581. */
  16582. this.onMaterialDispose = () => {
  16583. this.dispose();
  16584. };
  16585. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16586. }
  16587. /**
  16588. * Updates the clipping context.
  16589. *
  16590. * @param {ClippingContext} context - The clipping context to set.
  16591. */
  16592. updateClipping( context ) {
  16593. this.clippingContext = context;
  16594. }
  16595. /**
  16596. * Whether the clipping requires an update or not.
  16597. *
  16598. * @type {Boolean}
  16599. * @readonly
  16600. */
  16601. get clippingNeedsUpdate() {
  16602. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16603. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16604. return true;
  16605. }
  16606. /**
  16607. * The number of clipping planes defined in context of hardware clipping.
  16608. *
  16609. * @type {Number}
  16610. * @readonly
  16611. */
  16612. get hardwareClippingPlanes() {
  16613. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16614. }
  16615. /**
  16616. * Returns the node builder state of this render object.
  16617. *
  16618. * @return {NodeBuilderState} The node builder state.
  16619. */
  16620. getNodeBuilderState() {
  16621. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16622. }
  16623. /**
  16624. * Returns the node material observer of this render object.
  16625. *
  16626. * @return {NodeMaterialObserver} The node material observer.
  16627. */
  16628. getMonitor() {
  16629. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  16630. }
  16631. /**
  16632. * Returns an array of bind groups of this render object.
  16633. *
  16634. * @return {Array<BindGroup>} The bindings.
  16635. */
  16636. getBindings() {
  16637. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16638. }
  16639. /**
  16640. * Returns a binding group by group name of this render object.
  16641. *
  16642. * @param {String} name - The name of the binding group.
  16643. * @return {BindGroup?} The bindings.
  16644. */
  16645. getBindingGroup( name ) {
  16646. for ( const bindingGroup of this.getBindings() ) {
  16647. if ( bindingGroup.name === name ) {
  16648. return bindingGroup;
  16649. }
  16650. }
  16651. }
  16652. /**
  16653. * Returns the index of the render object's geometry.
  16654. *
  16655. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16656. */
  16657. getIndex() {
  16658. return this._geometries.getIndex( this );
  16659. }
  16660. /**
  16661. * Returns the indirect buffer attribute.
  16662. *
  16663. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16664. */
  16665. getIndirect() {
  16666. return this._geometries.getIndirect( this );
  16667. }
  16668. /**
  16669. * Returns an array that acts as a key for identifying the render object in a chain map.
  16670. *
  16671. * @return {Array<Object>} An array with object references.
  16672. */
  16673. getChainArray() {
  16674. return [ this.object, this.material, this.context, this.lightsNode ];
  16675. }
  16676. /**
  16677. * This method is used when the geometry of a 3D object has been exchanged and the
  16678. * respective render object now requires an update.
  16679. *
  16680. * @param {BufferGeometry} geometry - The geometry to set.
  16681. */
  16682. setGeometry( geometry ) {
  16683. this.geometry = geometry;
  16684. this.attributes = null;
  16685. }
  16686. /**
  16687. * Returns the buffer attributes of the render object. The returned array holds
  16688. * attribute definitions on geometry and node level.
  16689. *
  16690. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16691. */
  16692. getAttributes() {
  16693. if ( this.attributes !== null ) return this.attributes;
  16694. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16695. const geometry = this.geometry;
  16696. const attributes = [];
  16697. const vertexBuffers = new Set();
  16698. for ( const nodeAttribute of nodeAttributes ) {
  16699. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16700. if ( attribute === undefined ) continue;
  16701. attributes.push( attribute );
  16702. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16703. vertexBuffers.add( bufferAttribute );
  16704. }
  16705. this.attributes = attributes;
  16706. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16707. return attributes;
  16708. }
  16709. /**
  16710. * Returns the vertex buffers of the render object.
  16711. *
  16712. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16713. */
  16714. getVertexBuffers() {
  16715. if ( this.vertexBuffers === null ) this.getAttributes();
  16716. return this.vertexBuffers;
  16717. }
  16718. /**
  16719. * Returns the draw parameters for the render object.
  16720. *
  16721. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16722. */
  16723. getDrawParameters() {
  16724. const { object, material, geometry, group, drawRange } = this;
  16725. const drawParams = this.drawParams || ( this.drawParams = {
  16726. vertexCount: 0,
  16727. firstVertex: 0,
  16728. instanceCount: 0,
  16729. firstInstance: 0
  16730. } );
  16731. const index = this.getIndex();
  16732. const hasIndex = ( index !== null );
  16733. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16734. if ( instanceCount === 0 ) return null;
  16735. drawParams.instanceCount = instanceCount;
  16736. if ( object.isBatchedMesh === true ) return drawParams;
  16737. let rangeFactor = 1;
  16738. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16739. rangeFactor = 2;
  16740. }
  16741. let firstVertex = drawRange.start * rangeFactor;
  16742. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16743. if ( group !== null ) {
  16744. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16745. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16746. }
  16747. const position = geometry.attributes.position;
  16748. let itemCount = Infinity;
  16749. if ( hasIndex ) {
  16750. itemCount = index.count;
  16751. } else if ( position !== undefined && position !== null ) {
  16752. itemCount = position.count;
  16753. }
  16754. firstVertex = Math.max( firstVertex, 0 );
  16755. lastVertex = Math.min( lastVertex, itemCount );
  16756. const count = lastVertex - firstVertex;
  16757. if ( count < 0 || count === Infinity ) return null;
  16758. drawParams.vertexCount = count;
  16759. drawParams.firstVertex = firstVertex;
  16760. return drawParams;
  16761. }
  16762. /**
  16763. * Returns the render object's geometry cache key.
  16764. *
  16765. * The geometry cache key is part of the material cache key.
  16766. *
  16767. * @return {String} The geometry cache key.
  16768. */
  16769. getGeometryCacheKey() {
  16770. const { geometry } = this;
  16771. let cacheKey = '';
  16772. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16773. const attribute = geometry.attributes[ name ];
  16774. cacheKey += name + ',';
  16775. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16776. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16777. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16778. if ( attribute.normalized ) cacheKey += 'n,';
  16779. }
  16780. // structural equality isn't sufficient for morph targets since the
  16781. // data are maintained in textures. only if the targets are all equal
  16782. // the texture and thus the instance of `MorphNode` can be shared.
  16783. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  16784. const targets = geometry.morphAttributes[ name ];
  16785. cacheKey += 'morph-' + name + ',';
  16786. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  16787. const attribute = targets[ i ];
  16788. cacheKey += attribute.id + ',';
  16789. }
  16790. }
  16791. if ( geometry.index ) {
  16792. cacheKey += 'index,';
  16793. }
  16794. return cacheKey;
  16795. }
  16796. /**
  16797. * Returns the render object's material cache key.
  16798. *
  16799. * The material cache key is part of the render object cache key.
  16800. *
  16801. * @return {Number} The material cache key.
  16802. */
  16803. getMaterialCacheKey() {
  16804. const { object, material } = this;
  16805. let cacheKey = material.customProgramCacheKey();
  16806. for ( const property of getKeys( material ) ) {
  16807. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16808. const value = material[ property ];
  16809. let valueKey;
  16810. if ( value !== null ) {
  16811. // some material values require a formatting
  16812. const type = typeof value;
  16813. if ( type === 'number' ) {
  16814. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16815. } else if ( type === 'object' ) {
  16816. valueKey = '{';
  16817. if ( value.isTexture ) {
  16818. valueKey += value.mapping;
  16819. }
  16820. valueKey += '}';
  16821. } else {
  16822. valueKey = String( value );
  16823. }
  16824. } else {
  16825. valueKey = String( value );
  16826. }
  16827. cacheKey += /*property + ':' +*/ valueKey + ',';
  16828. }
  16829. cacheKey += this.clippingContextCacheKey + ',';
  16830. if ( object.geometry ) {
  16831. cacheKey += this.getGeometryCacheKey();
  16832. }
  16833. if ( object.skeleton ) {
  16834. cacheKey += object.skeleton.bones.length + ',';
  16835. }
  16836. if ( object.isBatchedMesh ) {
  16837. cacheKey += object._matricesTexture.uuid + ',';
  16838. if ( object._colorsTexture !== null ) {
  16839. cacheKey += object._colorsTexture.uuid + ',';
  16840. }
  16841. }
  16842. if ( object.count > 1 ) {
  16843. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16844. cacheKey += object.uuid + ',';
  16845. }
  16846. cacheKey += object.receiveShadow + ',';
  16847. return hashString( cacheKey );
  16848. }
  16849. /**
  16850. * Whether the geometry requires an update or not.
  16851. *
  16852. * @type {Boolean}
  16853. * @readonly
  16854. */
  16855. get needsGeometryUpdate() {
  16856. return this.geometry.id !== this.object.geometry.id;
  16857. }
  16858. /**
  16859. * Whether the render object requires an update or not.
  16860. *
  16861. * Note: There are two distinct places where render objects are checked for an update.
  16862. *
  16863. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16864. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16865. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16866. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16867. * a need for a refresh due to material, geometry or object related value changes.
  16868. *
  16869. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  16870. * that performs the 'needsUpdate' check.
  16871. *
  16872. * @type {Boolean}
  16873. * @readonly
  16874. */
  16875. get needsUpdate() {
  16876. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16877. }
  16878. /**
  16879. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16880. *
  16881. * @return {Number} The cache key.
  16882. */
  16883. getDynamicCacheKey() {
  16884. let cacheKey = 0;
  16885. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  16886. // the renderer is inside a shadow pass.
  16887. if ( this.material.isShadowPassMaterial !== true ) {
  16888. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16889. }
  16890. if ( this.camera.isArrayCamera ) {
  16891. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  16892. }
  16893. if ( this.object.receiveShadow ) {
  16894. cacheKey = hash$1( cacheKey, 1 );
  16895. }
  16896. return cacheKey;
  16897. }
  16898. /**
  16899. * Returns the render object's cache key.
  16900. *
  16901. * @return {Number} The cache key.
  16902. */
  16903. getCacheKey() {
  16904. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16905. }
  16906. /**
  16907. * Frees internal resources.
  16908. */
  16909. dispose() {
  16910. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16911. this.onDispose();
  16912. }
  16913. }
  16914. const _chainKeys$5 = [];
  16915. /**
  16916. * This module manages the render objects of the renderer.
  16917. *
  16918. * @private
  16919. */
  16920. class RenderObjects {
  16921. /**
  16922. * Constructs a new render object management component.
  16923. *
  16924. * @param {Renderer} renderer - The renderer.
  16925. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16926. * @param {Geometries} geometries - Renderer component for managing geometries.
  16927. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16928. * @param {Bindings} bindings - Renderer component for managing bindings.
  16929. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16930. */
  16931. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16932. /**
  16933. * The renderer.
  16934. *
  16935. * @type {Renderer}
  16936. */
  16937. this.renderer = renderer;
  16938. /**
  16939. * Renderer component for managing nodes related logic.
  16940. *
  16941. * @type {Nodes}
  16942. */
  16943. this.nodes = nodes;
  16944. /**
  16945. * Renderer component for managing geometries.
  16946. *
  16947. * @type {Geometries}
  16948. */
  16949. this.geometries = geometries;
  16950. /**
  16951. * Renderer component for managing pipelines.
  16952. *
  16953. * @type {Pipelines}
  16954. */
  16955. this.pipelines = pipelines;
  16956. /**
  16957. * Renderer component for managing bindings.
  16958. *
  16959. * @type {Bindings}
  16960. */
  16961. this.bindings = bindings;
  16962. /**
  16963. * Renderer component for managing metrics and monitoring data.
  16964. *
  16965. * @type {Info}
  16966. */
  16967. this.info = info;
  16968. /**
  16969. * A dictionary that manages render contexts in chain maps
  16970. * for each pass ID.
  16971. *
  16972. * @type {Object<String,ChainMap>}
  16973. */
  16974. this.chainMaps = {};
  16975. }
  16976. /**
  16977. * Returns a render object for the given object and state data.
  16978. *
  16979. * @param {Object3D} object - The 3D object.
  16980. * @param {Material} material - The 3D object's material.
  16981. * @param {Scene} scene - The scene the 3D object belongs to.
  16982. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16983. * @param {LightsNode} lightsNode - The lights node.
  16984. * @param {RenderContext} renderContext - The render context.
  16985. * @param {ClippingContext} clippingContext - The clipping context.
  16986. * @param {String?} passId - An optional ID for identifying the pass.
  16987. * @return {RenderObject} The render object.
  16988. */
  16989. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16990. const chainMap = this.getChainMap( passId );
  16991. // reuse chainArray
  16992. _chainKeys$5[ 0 ] = object;
  16993. _chainKeys$5[ 1 ] = material;
  16994. _chainKeys$5[ 2 ] = renderContext;
  16995. _chainKeys$5[ 3 ] = lightsNode;
  16996. let renderObject = chainMap.get( _chainKeys$5 );
  16997. if ( renderObject === undefined ) {
  16998. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16999. chainMap.set( _chainKeys$5, renderObject );
  17000. } else {
  17001. renderObject.updateClipping( clippingContext );
  17002. if ( renderObject.needsGeometryUpdate ) {
  17003. renderObject.setGeometry( object.geometry );
  17004. }
  17005. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  17006. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  17007. renderObject.dispose();
  17008. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  17009. } else {
  17010. renderObject.version = material.version;
  17011. }
  17012. }
  17013. }
  17014. _chainKeys$5.length = 0;
  17015. return renderObject;
  17016. }
  17017. /**
  17018. * Returns a chain map for the given pass ID.
  17019. *
  17020. * @param {String} [passId='default'] - The pass ID.
  17021. * @return {ChainMap} The chain map.
  17022. */
  17023. getChainMap( passId = 'default' ) {
  17024. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  17025. }
  17026. /**
  17027. * Frees internal resources.
  17028. */
  17029. dispose() {
  17030. this.chainMaps = {};
  17031. }
  17032. /**
  17033. * Factory method for creating render objects with the given list of parameters.
  17034. *
  17035. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17036. * @param {Geometries} geometries - Renderer component for managing geometries.
  17037. * @param {Renderer} renderer - The renderer.
  17038. * @param {Object3D} object - The 3D object.
  17039. * @param {Material} material - The object's material.
  17040. * @param {Scene} scene - The scene the 3D object belongs to.
  17041. * @param {Camera} camera - The camera the object should be rendered with.
  17042. * @param {LightsNode} lightsNode - The lights node.
  17043. * @param {RenderContext} renderContext - The render context.
  17044. * @param {ClippingContext} clippingContext - The clipping context.
  17045. * @param {String?} passId - An optional ID for identifying the pass.
  17046. * @return {RenderObject} The render object.
  17047. */
  17048. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  17049. const chainMap = this.getChainMap( passId );
  17050. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  17051. renderObject.onDispose = () => {
  17052. this.pipelines.delete( renderObject );
  17053. this.bindings.delete( renderObject );
  17054. this.nodes.delete( renderObject );
  17055. chainMap.delete( renderObject.getChainArray() );
  17056. };
  17057. return renderObject;
  17058. }
  17059. }
  17060. /**
  17061. * Data structure for the renderer. It is intended to manage
  17062. * data of objects in dictionaries.
  17063. *
  17064. * @private
  17065. */
  17066. class DataMap {
  17067. /**
  17068. * Constructs a new data map.
  17069. */
  17070. constructor() {
  17071. /**
  17072. * `DataMap` internally uses a weak map
  17073. * to manage its data.
  17074. *
  17075. * @type {WeakMap}
  17076. */
  17077. this.data = new WeakMap();
  17078. }
  17079. /**
  17080. * Returns the dictionary for the given object.
  17081. *
  17082. * @param {Object} object - The object.
  17083. * @return {Object} The dictionary.
  17084. */
  17085. get( object ) {
  17086. let map = this.data.get( object );
  17087. if ( map === undefined ) {
  17088. map = {};
  17089. this.data.set( object, map );
  17090. }
  17091. return map;
  17092. }
  17093. /**
  17094. * Deletes the dictionary for the given object.
  17095. *
  17096. * @param {Object} object - The object.
  17097. * @return {Object?} The deleted dictionary.
  17098. */
  17099. delete( object ) {
  17100. let map = null;
  17101. if ( this.data.has( object ) ) {
  17102. map = this.data.get( object );
  17103. this.data.delete( object );
  17104. }
  17105. return map;
  17106. }
  17107. /**
  17108. * Returns `true` if the given object has a dictionary defined.
  17109. *
  17110. * @param {Object} object - The object to test.
  17111. * @return {Boolean} Whether a dictionary is defined or not.
  17112. */
  17113. has( object ) {
  17114. return this.data.has( object );
  17115. }
  17116. /**
  17117. * Frees internal resources.
  17118. */
  17119. dispose() {
  17120. this.data = new WeakMap();
  17121. }
  17122. }
  17123. const AttributeType = {
  17124. VERTEX: 1,
  17125. INDEX: 2,
  17126. STORAGE: 3,
  17127. INDIRECT: 4
  17128. };
  17129. // size of a chunk in bytes (STD140 layout)
  17130. const GPU_CHUNK_BYTES = 16;
  17131. // @TODO: Move to src/constants.js
  17132. const BlendColorFactor = 211;
  17133. const OneMinusBlendColorFactor = 212;
  17134. /**
  17135. * This renderer module manages geometry attributes.
  17136. *
  17137. * @private
  17138. * @augments DataMap
  17139. */
  17140. class Attributes extends DataMap {
  17141. /**
  17142. * Constructs a new attribute management component.
  17143. *
  17144. * @param {Backend} backend - The renderer's backend.
  17145. */
  17146. constructor( backend ) {
  17147. super();
  17148. /**
  17149. * The renderer's backend.
  17150. *
  17151. * @type {Backend}
  17152. */
  17153. this.backend = backend;
  17154. }
  17155. /**
  17156. * Deletes the data for the given attribute.
  17157. *
  17158. * @param {BufferAttribute} attribute - The attribute.
  17159. * @return {Object} The deleted attribute data.
  17160. */
  17161. delete( attribute ) {
  17162. const attributeData = super.delete( attribute );
  17163. if ( attributeData !== undefined ) {
  17164. this.backend.destroyAttribute( attribute );
  17165. }
  17166. return attributeData;
  17167. }
  17168. /**
  17169. * Updates the given attribute. This method creates attribute buffers
  17170. * for new attributes and updates data for existing ones.
  17171. *
  17172. * @param {BufferAttribute} attribute - The attribute to update.
  17173. * @param {Number} type - The attribute type.
  17174. */
  17175. update( attribute, type ) {
  17176. const data = this.get( attribute );
  17177. if ( data.version === undefined ) {
  17178. if ( type === AttributeType.VERTEX ) {
  17179. this.backend.createAttribute( attribute );
  17180. } else if ( type === AttributeType.INDEX ) {
  17181. this.backend.createIndexAttribute( attribute );
  17182. } else if ( type === AttributeType.STORAGE ) {
  17183. this.backend.createStorageAttribute( attribute );
  17184. } else if ( type === AttributeType.INDIRECT ) {
  17185. this.backend.createIndirectStorageAttribute( attribute );
  17186. }
  17187. data.version = this._getBufferAttribute( attribute ).version;
  17188. } else {
  17189. const bufferAttribute = this._getBufferAttribute( attribute );
  17190. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  17191. this.backend.updateAttribute( attribute );
  17192. data.version = bufferAttribute.version;
  17193. }
  17194. }
  17195. }
  17196. /**
  17197. * Utility method for handling interleaved buffer attributes correctly.
  17198. * To process them, their `InterleavedBuffer` is returned.
  17199. *
  17200. * @param {BufferAttribute} attribute - The attribute.
  17201. * @return {BufferAttribute|InterleavedBuffer}
  17202. */
  17203. _getBufferAttribute( attribute ) {
  17204. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  17205. return attribute;
  17206. }
  17207. }
  17208. /**
  17209. * Returns the wireframe version for the given geometry.
  17210. *
  17211. * @private
  17212. * @function
  17213. * @param {BufferGeometry} geometry - The geometry.
  17214. * @return {Number} The version.
  17215. */
  17216. function getWireframeVersion( geometry ) {
  17217. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  17218. }
  17219. /**
  17220. * Returns a wireframe index attribute for the given geometry.
  17221. *
  17222. * @private
  17223. * @function
  17224. * @param {BufferGeometry} geometry - The geometry.
  17225. * @return {BufferAttribute} The wireframe index attribute.
  17226. */
  17227. function getWireframeIndex( geometry ) {
  17228. const indices = [];
  17229. const geometryIndex = geometry.index;
  17230. const geometryPosition = geometry.attributes.position;
  17231. if ( geometryIndex !== null ) {
  17232. const array = geometryIndex.array;
  17233. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  17234. const a = array[ i + 0 ];
  17235. const b = array[ i + 1 ];
  17236. const c = array[ i + 2 ];
  17237. indices.push( a, b, b, c, c, a );
  17238. }
  17239. } else {
  17240. const array = geometryPosition.array;
  17241. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17242. const a = i + 0;
  17243. const b = i + 1;
  17244. const c = i + 2;
  17245. indices.push( a, b, b, c, c, a );
  17246. }
  17247. }
  17248. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  17249. attribute.version = getWireframeVersion( geometry );
  17250. return attribute;
  17251. }
  17252. /**
  17253. * This renderer module manages geometries.
  17254. *
  17255. * @private
  17256. * @augments DataMap
  17257. */
  17258. class Geometries extends DataMap {
  17259. /**
  17260. * Constructs a new geometry management component.
  17261. *
  17262. * @param {Attributes} attributes - Renderer component for managing attributes.
  17263. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17264. */
  17265. constructor( attributes, info ) {
  17266. super();
  17267. /**
  17268. * Renderer component for managing attributes.
  17269. *
  17270. * @type {Attributes}
  17271. */
  17272. this.attributes = attributes;
  17273. /**
  17274. * Renderer component for managing metrics and monitoring data.
  17275. *
  17276. * @type {Info}
  17277. */
  17278. this.info = info;
  17279. /**
  17280. * Weak Map for managing attributes for wireframe rendering.
  17281. *
  17282. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  17283. */
  17284. this.wireframes = new WeakMap();
  17285. /**
  17286. * This Weak Map is used to make sure buffer attributes are
  17287. * updated only once per render call.
  17288. *
  17289. * @type {WeakMap<BufferAttribute,Number>}
  17290. */
  17291. this.attributeCall = new WeakMap();
  17292. }
  17293. /**
  17294. * Returns `true` if the given render object has an initialized geometry.
  17295. *
  17296. * @param {RenderObject} renderObject - The render object.
  17297. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  17298. */
  17299. has( renderObject ) {
  17300. const geometry = renderObject.geometry;
  17301. return super.has( geometry ) && this.get( geometry ).initialized === true;
  17302. }
  17303. /**
  17304. * Prepares the geometry of the given render object for rendering.
  17305. *
  17306. * @param {RenderObject} renderObject - The render object.
  17307. */
  17308. updateForRender( renderObject ) {
  17309. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  17310. this.updateAttributes( renderObject );
  17311. }
  17312. /**
  17313. * Initializes the geometry of the given render object.
  17314. *
  17315. * @param {RenderObject} renderObject - The render object.
  17316. */
  17317. initGeometry( renderObject ) {
  17318. const geometry = renderObject.geometry;
  17319. const geometryData = this.get( geometry );
  17320. geometryData.initialized = true;
  17321. this.info.memory.geometries ++;
  17322. const onDispose = () => {
  17323. this.info.memory.geometries --;
  17324. const index = geometry.index;
  17325. const geometryAttributes = renderObject.getAttributes();
  17326. if ( index !== null ) {
  17327. this.attributes.delete( index );
  17328. }
  17329. for ( const geometryAttribute of geometryAttributes ) {
  17330. this.attributes.delete( geometryAttribute );
  17331. }
  17332. const wireframeAttribute = this.wireframes.get( geometry );
  17333. if ( wireframeAttribute !== undefined ) {
  17334. this.attributes.delete( wireframeAttribute );
  17335. }
  17336. geometry.removeEventListener( 'dispose', onDispose );
  17337. };
  17338. geometry.addEventListener( 'dispose', onDispose );
  17339. }
  17340. /**
  17341. * Updates the geometry attributes of the given render object.
  17342. *
  17343. * @param {RenderObject} renderObject - The render object.
  17344. */
  17345. updateAttributes( renderObject ) {
  17346. // attributes
  17347. const attributes = renderObject.getAttributes();
  17348. for ( const attribute of attributes ) {
  17349. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17350. this.updateAttribute( attribute, AttributeType.STORAGE );
  17351. } else {
  17352. this.updateAttribute( attribute, AttributeType.VERTEX );
  17353. }
  17354. }
  17355. // indexes
  17356. const index = this.getIndex( renderObject );
  17357. if ( index !== null ) {
  17358. this.updateAttribute( index, AttributeType.INDEX );
  17359. }
  17360. // indirect
  17361. const indirect = renderObject.geometry.indirect;
  17362. if ( indirect !== null ) {
  17363. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17364. }
  17365. }
  17366. /**
  17367. * Updates the given attribute.
  17368. *
  17369. * @param {BufferAttribute} attribute - The attribute to update.
  17370. * @param {Number} type - The attribute type.
  17371. */
  17372. updateAttribute( attribute, type ) {
  17373. const callId = this.info.render.calls;
  17374. if ( ! attribute.isInterleavedBufferAttribute ) {
  17375. if ( this.attributeCall.get( attribute ) !== callId ) {
  17376. this.attributes.update( attribute, type );
  17377. this.attributeCall.set( attribute, callId );
  17378. }
  17379. } else {
  17380. if ( this.attributeCall.get( attribute ) === undefined ) {
  17381. this.attributes.update( attribute, type );
  17382. this.attributeCall.set( attribute, callId );
  17383. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17384. this.attributes.update( attribute, type );
  17385. this.attributeCall.set( attribute.data, callId );
  17386. this.attributeCall.set( attribute, callId );
  17387. }
  17388. }
  17389. }
  17390. /**
  17391. * Returns the indirect buffer attribute of the given render object.
  17392. *
  17393. * @param {RenderObject} renderObject - The render object.
  17394. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17395. */
  17396. getIndirect( renderObject ) {
  17397. return renderObject.geometry.indirect;
  17398. }
  17399. /**
  17400. * Returns the index of the given render object's geometry. This is implemented
  17401. * in a method to return a wireframe index if necessary.
  17402. *
  17403. * @param {RenderObject} renderObject - The render object.
  17404. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17405. */
  17406. getIndex( renderObject ) {
  17407. const { geometry, material } = renderObject;
  17408. let index = geometry.index;
  17409. if ( material.wireframe === true ) {
  17410. const wireframes = this.wireframes;
  17411. let wireframeAttribute = wireframes.get( geometry );
  17412. if ( wireframeAttribute === undefined ) {
  17413. wireframeAttribute = getWireframeIndex( geometry );
  17414. wireframes.set( geometry, wireframeAttribute );
  17415. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17416. this.attributes.delete( wireframeAttribute );
  17417. wireframeAttribute = getWireframeIndex( geometry );
  17418. wireframes.set( geometry, wireframeAttribute );
  17419. }
  17420. index = wireframeAttribute;
  17421. }
  17422. return index;
  17423. }
  17424. }
  17425. /**
  17426. * This renderer module provides a series of statistical information
  17427. * about the GPU memory and the rendering process. Useful for debugging
  17428. * and monitoring.
  17429. */
  17430. class Info {
  17431. /**
  17432. * Constructs a new info component.
  17433. */
  17434. constructor() {
  17435. /**
  17436. * Whether frame related metrics should automatically
  17437. * be resetted or not. This property should be set to `false`
  17438. * by apps which manage their own animation loop. They must
  17439. * then call `renderer.info.reset()` once per frame manually.
  17440. *
  17441. * @type {Boolean}
  17442. * @default true
  17443. */
  17444. this.autoReset = true;
  17445. /**
  17446. * The current frame ID. This ID is managed
  17447. * by `NodeFrame`.
  17448. *
  17449. * @type {Number}
  17450. * @readonly
  17451. * @default 0
  17452. */
  17453. this.frame = 0;
  17454. /**
  17455. * The number of render calls since the
  17456. * app has been started.
  17457. *
  17458. * @type {Number}
  17459. * @readonly
  17460. * @default 0
  17461. */
  17462. this.calls = 0;
  17463. /**
  17464. * Render related metrics.
  17465. *
  17466. * @type {Object}
  17467. * @readonly
  17468. * @property {Number} calls - The number of render calls since the app has been started.
  17469. * @property {Number} frameCalls - The number of render calls of the current frame.
  17470. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17471. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17472. * @property {Number} points - The number of rendered point primitives of the current frame.
  17473. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17474. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17475. */
  17476. this.render = {
  17477. calls: 0,
  17478. frameCalls: 0,
  17479. drawCalls: 0,
  17480. triangles: 0,
  17481. points: 0,
  17482. lines: 0,
  17483. timestamp: 0,
  17484. };
  17485. /**
  17486. * Compute related metrics.
  17487. *
  17488. * @type {Object}
  17489. * @readonly
  17490. * @property {Number} calls - The number of compute calls since the app has been started.
  17491. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17492. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17493. */
  17494. this.compute = {
  17495. calls: 0,
  17496. frameCalls: 0,
  17497. timestamp: 0
  17498. };
  17499. /**
  17500. * Memory related metrics.
  17501. *
  17502. * @type {Object}
  17503. * @readonly
  17504. * @property {Number} geometries - The number of active geometries.
  17505. * @property {Number} frameCalls - The number of active textures.
  17506. */
  17507. this.memory = {
  17508. geometries: 0,
  17509. textures: 0
  17510. };
  17511. }
  17512. /**
  17513. * This method should be executed per draw call and updates the corresponding metrics.
  17514. *
  17515. * @param {Object3D} object - The 3D object that is going to be rendered.
  17516. * @param {Number} count - The vertex or index count.
  17517. * @param {Number} instanceCount - The instance count.
  17518. */
  17519. update( object, count, instanceCount ) {
  17520. this.render.drawCalls ++;
  17521. if ( object.isMesh || object.isSprite ) {
  17522. this.render.triangles += instanceCount * ( count / 3 );
  17523. } else if ( object.isPoints ) {
  17524. this.render.points += instanceCount * count;
  17525. } else if ( object.isLineSegments ) {
  17526. this.render.lines += instanceCount * ( count / 2 );
  17527. } else if ( object.isLine ) {
  17528. this.render.lines += instanceCount * ( count - 1 );
  17529. } else {
  17530. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17531. }
  17532. }
  17533. /**
  17534. * Resets frame related metrics.
  17535. */
  17536. reset() {
  17537. this.render.drawCalls = 0;
  17538. this.render.frameCalls = 0;
  17539. this.compute.frameCalls = 0;
  17540. this.render.triangles = 0;
  17541. this.render.points = 0;
  17542. this.render.lines = 0;
  17543. }
  17544. /**
  17545. * Performs a complete reset of the object.
  17546. */
  17547. dispose() {
  17548. this.reset();
  17549. this.calls = 0;
  17550. this.render.calls = 0;
  17551. this.compute.calls = 0;
  17552. this.render.timestamp = 0;
  17553. this.compute.timestamp = 0;
  17554. this.memory.geometries = 0;
  17555. this.memory.textures = 0;
  17556. }
  17557. }
  17558. /**
  17559. * Abstract class for representing pipelines.
  17560. *
  17561. * @private
  17562. * @abstract
  17563. */
  17564. class Pipeline {
  17565. /**
  17566. * Constructs a new pipeline.
  17567. *
  17568. * @param {String} cacheKey - The pipeline's cache key.
  17569. */
  17570. constructor( cacheKey ) {
  17571. /**
  17572. * The pipeline's cache key.
  17573. *
  17574. * @type {String}
  17575. */
  17576. this.cacheKey = cacheKey;
  17577. /**
  17578. * How often the pipeline is currently in use.
  17579. *
  17580. * @type {Number}
  17581. * @default 0
  17582. */
  17583. this.usedTimes = 0;
  17584. }
  17585. }
  17586. /**
  17587. * Class for representing render pipelines.
  17588. *
  17589. * @private
  17590. * @augments Pipeline
  17591. */
  17592. class RenderPipeline extends Pipeline {
  17593. /**
  17594. * Constructs a new render pipeline.
  17595. *
  17596. * @param {String} cacheKey - The pipeline's cache key.
  17597. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17598. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17599. */
  17600. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17601. super( cacheKey );
  17602. /**
  17603. * The pipeline's vertex shader.
  17604. *
  17605. * @type {ProgrammableStage}
  17606. */
  17607. this.vertexProgram = vertexProgram;
  17608. /**
  17609. * The pipeline's fragment shader.
  17610. *
  17611. * @type {ProgrammableStage}
  17612. */
  17613. this.fragmentProgram = fragmentProgram;
  17614. }
  17615. }
  17616. /**
  17617. * Class for representing compute pipelines.
  17618. *
  17619. * @private
  17620. * @augments Pipeline
  17621. */
  17622. class ComputePipeline extends Pipeline {
  17623. /**
  17624. * Constructs a new render pipeline.
  17625. *
  17626. * @param {String} cacheKey - The pipeline's cache key.
  17627. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17628. */
  17629. constructor( cacheKey, computeProgram ) {
  17630. super( cacheKey );
  17631. /**
  17632. * The pipeline's compute shader.
  17633. *
  17634. * @type {ProgrammableStage}
  17635. */
  17636. this.computeProgram = computeProgram;
  17637. /**
  17638. * This flag can be used for type testing.
  17639. *
  17640. * @type {Boolean}
  17641. * @readonly
  17642. * @default true
  17643. */
  17644. this.isComputePipeline = true;
  17645. }
  17646. }
  17647. let _id$8 = 0;
  17648. /**
  17649. * Class for representing programmable stages which are vertex,
  17650. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17651. * they represent the programmable part of a pipeline.
  17652. *
  17653. * @private
  17654. */
  17655. class ProgrammableStage {
  17656. /**
  17657. * Constructs a new programmable stage.
  17658. *
  17659. * @param {String} code - The shader code.
  17660. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17661. * @param {String} name - The name of the shader.
  17662. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17663. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17664. */
  17665. constructor( code, stage, name, transforms = null, attributes = null ) {
  17666. /**
  17667. * The id of the programmable stage.
  17668. *
  17669. * @type {Number}
  17670. */
  17671. this.id = _id$8 ++;
  17672. /**
  17673. * The shader code.
  17674. *
  17675. * @type {String}
  17676. */
  17677. this.code = code;
  17678. /**
  17679. * The type of stage.
  17680. *
  17681. * @type {String}
  17682. */
  17683. this.stage = stage;
  17684. /**
  17685. * The name of the stage.
  17686. * This is used for debugging purposes.
  17687. *
  17688. * @type {String}
  17689. */
  17690. this.name = name;
  17691. /**
  17692. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17693. *
  17694. * @type {Array<Object>?}
  17695. */
  17696. this.transforms = transforms;
  17697. /**
  17698. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17699. *
  17700. * @type {Array<Object>?}
  17701. */
  17702. this.attributes = attributes;
  17703. /**
  17704. * How often the programmable stage is currently in use.
  17705. *
  17706. * @type {Number}
  17707. * @default 0
  17708. */
  17709. this.usedTimes = 0;
  17710. }
  17711. }
  17712. /**
  17713. * This renderer module manages the pipelines of the renderer.
  17714. *
  17715. * @private
  17716. * @augments DataMap
  17717. */
  17718. class Pipelines extends DataMap {
  17719. /**
  17720. * Constructs a new pipeline management component.
  17721. *
  17722. * @param {Backend} backend - The renderer's backend.
  17723. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17724. */
  17725. constructor( backend, nodes ) {
  17726. super();
  17727. /**
  17728. * The renderer's backend.
  17729. *
  17730. * @type {Backend}
  17731. */
  17732. this.backend = backend;
  17733. /**
  17734. * Renderer component for managing nodes related logic.
  17735. *
  17736. * @type {Nodes}
  17737. */
  17738. this.nodes = nodes;
  17739. /**
  17740. * A references to the bindings management component.
  17741. * This reference will be set inside the `Bindings`
  17742. * constructor.
  17743. *
  17744. * @type {Bindings?}
  17745. * @default null
  17746. */
  17747. this.bindings = null;
  17748. /**
  17749. * Internal cache for maintaining pipelines.
  17750. * The key of the map is a cache key, the value the pipeline.
  17751. *
  17752. * @type {Map<String,Pipeline>}
  17753. */
  17754. this.caches = new Map();
  17755. /**
  17756. * This dictionary maintains for each shader stage type (vertex,
  17757. * fragment and compute) the programmable stage objects which
  17758. * represent the actual shader code.
  17759. *
  17760. * @type {Object<String,Map>}
  17761. */
  17762. this.programs = {
  17763. vertex: new Map(),
  17764. fragment: new Map(),
  17765. compute: new Map()
  17766. };
  17767. }
  17768. /**
  17769. * Returns a compute pipeline for the given compute node.
  17770. *
  17771. * @param {Node} computeNode - The compute node.
  17772. * @param {Array<BindGroup>} bindings - The bindings.
  17773. * @return {ComputePipeline} The compute pipeline.
  17774. */
  17775. getForCompute( computeNode, bindings ) {
  17776. const { backend } = this;
  17777. const data = this.get( computeNode );
  17778. if ( this._needsComputeUpdate( computeNode ) ) {
  17779. const previousPipeline = data.pipeline;
  17780. if ( previousPipeline ) {
  17781. previousPipeline.usedTimes --;
  17782. previousPipeline.computeProgram.usedTimes --;
  17783. }
  17784. // get shader
  17785. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17786. // programmable stage
  17787. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17788. if ( stageCompute === undefined ) {
  17789. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17790. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17791. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17792. backend.createProgram( stageCompute );
  17793. }
  17794. // determine compute pipeline
  17795. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17796. let pipeline = this.caches.get( cacheKey );
  17797. if ( pipeline === undefined ) {
  17798. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17799. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17800. }
  17801. // keep track of all used times
  17802. pipeline.usedTimes ++;
  17803. stageCompute.usedTimes ++;
  17804. //
  17805. data.version = computeNode.version;
  17806. data.pipeline = pipeline;
  17807. }
  17808. return data.pipeline;
  17809. }
  17810. /**
  17811. * Returns a render pipeline for the given render object.
  17812. *
  17813. * @param {RenderObject} renderObject - The render object.
  17814. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17815. * @return {RenderPipeline} The render pipeline.
  17816. */
  17817. getForRender( renderObject, promises = null ) {
  17818. const { backend } = this;
  17819. const data = this.get( renderObject );
  17820. if ( this._needsRenderUpdate( renderObject ) ) {
  17821. const previousPipeline = data.pipeline;
  17822. if ( previousPipeline ) {
  17823. previousPipeline.usedTimes --;
  17824. previousPipeline.vertexProgram.usedTimes --;
  17825. previousPipeline.fragmentProgram.usedTimes --;
  17826. }
  17827. // get shader
  17828. const nodeBuilderState = renderObject.getNodeBuilderState();
  17829. const name = renderObject.material ? renderObject.material.name : '';
  17830. // programmable stages
  17831. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17832. if ( stageVertex === undefined ) {
  17833. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17834. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17835. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17836. backend.createProgram( stageVertex );
  17837. }
  17838. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17839. if ( stageFragment === undefined ) {
  17840. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17841. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17842. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17843. backend.createProgram( stageFragment );
  17844. }
  17845. // determine render pipeline
  17846. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17847. let pipeline = this.caches.get( cacheKey );
  17848. if ( pipeline === undefined ) {
  17849. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17850. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17851. } else {
  17852. renderObject.pipeline = pipeline;
  17853. }
  17854. // keep track of all used times
  17855. pipeline.usedTimes ++;
  17856. stageVertex.usedTimes ++;
  17857. stageFragment.usedTimes ++;
  17858. //
  17859. data.pipeline = pipeline;
  17860. }
  17861. return data.pipeline;
  17862. }
  17863. /**
  17864. * Deletes the pipeline for the given render object.
  17865. *
  17866. * @param {RenderObject} object - The render object.
  17867. * @return {Object?} The deleted dictionary.
  17868. */
  17869. delete( object ) {
  17870. const pipeline = this.get( object ).pipeline;
  17871. if ( pipeline ) {
  17872. // pipeline
  17873. pipeline.usedTimes --;
  17874. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17875. // programs
  17876. if ( pipeline.isComputePipeline ) {
  17877. pipeline.computeProgram.usedTimes --;
  17878. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17879. } else {
  17880. pipeline.fragmentProgram.usedTimes --;
  17881. pipeline.vertexProgram.usedTimes --;
  17882. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17883. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17884. }
  17885. }
  17886. return super.delete( object );
  17887. }
  17888. /**
  17889. * Frees internal resources.
  17890. */
  17891. dispose() {
  17892. super.dispose();
  17893. this.caches = new Map();
  17894. this.programs = {
  17895. vertex: new Map(),
  17896. fragment: new Map(),
  17897. compute: new Map()
  17898. };
  17899. }
  17900. /**
  17901. * Updates the pipeline for the given render object.
  17902. *
  17903. * @param {RenderObject} renderObject - The render object.
  17904. */
  17905. updateForRender( renderObject ) {
  17906. this.getForRender( renderObject );
  17907. }
  17908. /**
  17909. * Returns a compute pipeline for the given parameters.
  17910. *
  17911. * @private
  17912. * @param {Node} computeNode - The compute node.
  17913. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17914. * @param {String} cacheKey - The cache key.
  17915. * @param {Array<BindGroup>} bindings - The bindings.
  17916. * @return {ComputePipeline} The compute pipeline.
  17917. */
  17918. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17919. // check for existing pipeline
  17920. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17921. let pipeline = this.caches.get( cacheKey );
  17922. if ( pipeline === undefined ) {
  17923. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17924. this.caches.set( cacheKey, pipeline );
  17925. this.backend.createComputePipeline( pipeline, bindings );
  17926. }
  17927. return pipeline;
  17928. }
  17929. /**
  17930. * Returns a render pipeline for the given parameters.
  17931. *
  17932. * @private
  17933. * @param {RenderObject} renderObject - The render object.
  17934. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17935. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17936. * @param {String} cacheKey - The cache key.
  17937. * @param {Array<Promise>?} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17938. * @return {ComputePipeline} The compute pipeline.
  17939. */
  17940. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17941. // check for existing pipeline
  17942. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17943. let pipeline = this.caches.get( cacheKey );
  17944. if ( pipeline === undefined ) {
  17945. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17946. this.caches.set( cacheKey, pipeline );
  17947. renderObject.pipeline = pipeline;
  17948. // The `promises` array is `null` by default and only set to an empty array when
  17949. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17950. // pending promises that resolve when the render pipelines are ready for rendering.
  17951. this.backend.createRenderPipeline( renderObject, promises );
  17952. }
  17953. return pipeline;
  17954. }
  17955. /**
  17956. * Computes a cache key representing a compute pipeline.
  17957. *
  17958. * @private
  17959. * @param {Node} computeNode - The compute node.
  17960. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17961. * @return {String} The cache key.
  17962. */
  17963. _getComputeCacheKey( computeNode, stageCompute ) {
  17964. return computeNode.id + ',' + stageCompute.id;
  17965. }
  17966. /**
  17967. * Computes a cache key representing a render pipeline.
  17968. *
  17969. * @private
  17970. * @param {RenderObject} renderObject - The render object.
  17971. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17972. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17973. * @return {String} The cache key.
  17974. */
  17975. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17976. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17977. }
  17978. /**
  17979. * Releases the given pipeline.
  17980. *
  17981. * @private
  17982. * @param {Pipeline} pipeline - The pipeline to release.
  17983. */
  17984. _releasePipeline( pipeline ) {
  17985. this.caches.delete( pipeline.cacheKey );
  17986. }
  17987. /**
  17988. * Releases the shader program.
  17989. *
  17990. * @private
  17991. * @param {Object} program - The shader program to release.
  17992. */
  17993. _releaseProgram( program ) {
  17994. const code = program.code;
  17995. const stage = program.stage;
  17996. this.programs[ stage ].delete( code );
  17997. }
  17998. /**
  17999. * Returns `true` if the compute pipeline for the given compute node requires an update.
  18000. *
  18001. * @private
  18002. * @param {Node} computeNode - The compute node.
  18003. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  18004. */
  18005. _needsComputeUpdate( computeNode ) {
  18006. const data = this.get( computeNode );
  18007. return data.pipeline === undefined || data.version !== computeNode.version;
  18008. }
  18009. /**
  18010. * Returns `true` if the render pipeline for the given render object requires an update.
  18011. *
  18012. * @private
  18013. * @param {RenderObject} renderObject - The render object.
  18014. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  18015. */
  18016. _needsRenderUpdate( renderObject ) {
  18017. const data = this.get( renderObject );
  18018. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  18019. }
  18020. }
  18021. /**
  18022. * This renderer module manages the bindings of the renderer.
  18023. *
  18024. * @private
  18025. * @augments DataMap
  18026. */
  18027. class Bindings extends DataMap {
  18028. /**
  18029. * Constructs a new bindings management component.
  18030. *
  18031. * @param {Backend} backend - The renderer's backend.
  18032. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18033. * @param {Textures} textures - Renderer component for managing textures.
  18034. * @param {Attributes} attributes - Renderer component for managing attributes.
  18035. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  18036. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18037. */
  18038. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  18039. super();
  18040. /**
  18041. * The renderer's backend.
  18042. *
  18043. * @type {Backend}
  18044. */
  18045. this.backend = backend;
  18046. /**
  18047. * Renderer component for managing textures.
  18048. *
  18049. * @type {Textures}
  18050. */
  18051. this.textures = textures;
  18052. /**
  18053. * Renderer component for managing pipelines.
  18054. *
  18055. * @type {Pipelines}
  18056. */
  18057. this.pipelines = pipelines;
  18058. /**
  18059. * Renderer component for managing attributes.
  18060. *
  18061. * @type {Attributes}
  18062. */
  18063. this.attributes = attributes;
  18064. /**
  18065. * Renderer component for managing nodes related logic.
  18066. *
  18067. * @type {Nodes}
  18068. */
  18069. this.nodes = nodes;
  18070. /**
  18071. * Renderer component for managing metrics and monitoring data.
  18072. *
  18073. * @type {Info}
  18074. */
  18075. this.info = info;
  18076. this.pipelines.bindings = this; // assign bindings to pipelines
  18077. }
  18078. /**
  18079. * Returns the bind groups for the given render object.
  18080. *
  18081. * @param {RenderObject} renderObject - The render object.
  18082. * @return {Array<BindGroup>} The bind groups.
  18083. */
  18084. getForRender( renderObject ) {
  18085. const bindings = renderObject.getBindings();
  18086. for ( const bindGroup of bindings ) {
  18087. const groupData = this.get( bindGroup );
  18088. if ( groupData.bindGroup === undefined ) {
  18089. // each object defines an array of bindings (ubos, textures, samplers etc.)
  18090. this._init( bindGroup );
  18091. this.backend.createBindings( bindGroup, bindings, 0 );
  18092. groupData.bindGroup = bindGroup;
  18093. }
  18094. }
  18095. return bindings;
  18096. }
  18097. /**
  18098. * Returns the bind groups for the given compute node.
  18099. *
  18100. * @param {Node} computeNode - The compute node.
  18101. * @return {Array<BindGroup>} The bind groups.
  18102. */
  18103. getForCompute( computeNode ) {
  18104. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  18105. for ( const bindGroup of bindings ) {
  18106. const groupData = this.get( bindGroup );
  18107. if ( groupData.bindGroup === undefined ) {
  18108. this._init( bindGroup );
  18109. this.backend.createBindings( bindGroup, bindings, 0 );
  18110. groupData.bindGroup = bindGroup;
  18111. }
  18112. }
  18113. return bindings;
  18114. }
  18115. /**
  18116. * Updates the bindings for the given compute node.
  18117. *
  18118. * @param {Node} computeNode - The compute node.
  18119. */
  18120. updateForCompute( computeNode ) {
  18121. this._updateBindings( this.getForCompute( computeNode ) );
  18122. }
  18123. /**
  18124. * Updates the bindings for the given render object.
  18125. *
  18126. * @param {RenderObject} renderObject - The render object.
  18127. */
  18128. updateForRender( renderObject ) {
  18129. this._updateBindings( this.getForRender( renderObject ) );
  18130. }
  18131. /**
  18132. * Updates the given array of bindings.
  18133. *
  18134. * @param {Array<BindGroup>} bindings - The bind groups.
  18135. */
  18136. _updateBindings( bindings ) {
  18137. for ( const bindGroup of bindings ) {
  18138. this._update( bindGroup, bindings );
  18139. }
  18140. }
  18141. /**
  18142. * Initializes the given bind group.
  18143. *
  18144. * @param {BindGroup} bindGroup - The bind group to initialize.
  18145. */
  18146. _init( bindGroup ) {
  18147. for ( const binding of bindGroup.bindings ) {
  18148. if ( binding.isSampledTexture ) {
  18149. this.textures.updateTexture( binding.texture );
  18150. } else if ( binding.isStorageBuffer ) {
  18151. const attribute = binding.attribute;
  18152. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  18153. this.attributes.update( attribute, attributeType );
  18154. }
  18155. }
  18156. }
  18157. /**
  18158. * Updates the given bind group.
  18159. *
  18160. * @param {BindGroup} bindGroup - The bind group to update.
  18161. * @param {Array<BindGroup>} bindings - The bind groups.
  18162. */
  18163. _update( bindGroup, bindings ) {
  18164. const { backend } = this;
  18165. let needsBindingsUpdate = false;
  18166. let cacheBindings = true;
  18167. let cacheIndex = 0;
  18168. let version = 0;
  18169. // iterate over all bindings and check if buffer updates or a new binding group is required
  18170. for ( const binding of bindGroup.bindings ) {
  18171. if ( binding.isNodeUniformsGroup ) {
  18172. const updated = this.nodes.updateGroup( binding );
  18173. // every uniforms group is a uniform buffer. So if no update is required,
  18174. // we move one with the next binding. Otherwise the next if block will update the group.
  18175. if ( updated === false ) continue;
  18176. }
  18177. if ( binding.isUniformBuffer ) {
  18178. const updated = binding.update();
  18179. if ( updated ) {
  18180. backend.updateBinding( binding );
  18181. }
  18182. } else if ( binding.isSampler ) {
  18183. binding.update();
  18184. } else if ( binding.isSampledTexture ) {
  18185. const texturesTextureData = this.textures.get( binding.texture );
  18186. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  18187. const updated = binding.update();
  18188. const texture = binding.texture;
  18189. if ( updated ) {
  18190. this.textures.updateTexture( texture );
  18191. }
  18192. const textureData = backend.get( texture );
  18193. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  18194. cacheBindings = false;
  18195. } else {
  18196. cacheIndex = cacheIndex * 10 + texture.id;
  18197. version += texture.version;
  18198. }
  18199. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  18200. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  18201. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  18202. this.textures.updateTexture( texture );
  18203. needsBindingsUpdate = true;
  18204. }
  18205. if ( texture.isStorageTexture === true ) {
  18206. const textureData = this.get( texture );
  18207. if ( binding.store === true ) {
  18208. textureData.needsMipmap = true;
  18209. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  18210. this.backend.generateMipmaps( texture );
  18211. textureData.needsMipmap = false;
  18212. }
  18213. }
  18214. }
  18215. }
  18216. if ( needsBindingsUpdate === true ) {
  18217. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  18218. }
  18219. }
  18220. }
  18221. /**
  18222. * Default sorting function for opaque render items.
  18223. *
  18224. * @private
  18225. * @function
  18226. * @param {Object} a - The first render item.
  18227. * @param {Object} b - The second render item.
  18228. * @return {Number} A numeric value which defines the sort order.
  18229. */
  18230. function painterSortStable( a, b ) {
  18231. if ( a.groupOrder !== b.groupOrder ) {
  18232. return a.groupOrder - b.groupOrder;
  18233. } else if ( a.renderOrder !== b.renderOrder ) {
  18234. return a.renderOrder - b.renderOrder;
  18235. } else if ( a.material.id !== b.material.id ) {
  18236. return a.material.id - b.material.id;
  18237. } else if ( a.z !== b.z ) {
  18238. return a.z - b.z;
  18239. } else {
  18240. return a.id - b.id;
  18241. }
  18242. }
  18243. /**
  18244. * Default sorting function for transparent render items.
  18245. *
  18246. * @private
  18247. * @function
  18248. * @param {Object} a - The first render item.
  18249. * @param {Object} b - The second render item.
  18250. * @return {Number} A numeric value which defines the sort order.
  18251. */
  18252. function reversePainterSortStable( a, b ) {
  18253. if ( a.groupOrder !== b.groupOrder ) {
  18254. return a.groupOrder - b.groupOrder;
  18255. } else if ( a.renderOrder !== b.renderOrder ) {
  18256. return a.renderOrder - b.renderOrder;
  18257. } else if ( a.z !== b.z ) {
  18258. return b.z - a.z;
  18259. } else {
  18260. return a.id - b.id;
  18261. }
  18262. }
  18263. /**
  18264. * Returns `true` if the given transparent material requires a double pass.
  18265. *
  18266. * @private
  18267. * @function
  18268. * @param {Material} material - The transparent material.
  18269. * @return {Boolean} Whether the given material requires a double pass or not.
  18270. */
  18271. function needsDoublePass( material ) {
  18272. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  18273. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  18274. }
  18275. /**
  18276. * When the renderer analyzes the scene at the beginning of a render call,
  18277. * it stores 3D object for further processing in render lists. Depending on the
  18278. * properties of a 3D objects (like their transformation or material state), the
  18279. * objects are maintained in ordered lists for the actual rendering.
  18280. *
  18281. * Render lists are unique per scene and camera combination.
  18282. *
  18283. * @private
  18284. * @augments Pipeline
  18285. */
  18286. class RenderList {
  18287. /**
  18288. * Constructs a render list.
  18289. *
  18290. * @param {Lighting} lighting - The lighting management component.
  18291. * @param {Scene} scene - The scene.
  18292. * @param {Camera} camera - The camera the scene is rendered with.
  18293. */
  18294. constructor( lighting, scene, camera ) {
  18295. /**
  18296. * 3D objects are transformed into render items and stored in this array.
  18297. *
  18298. * @type {Array<Object>}
  18299. */
  18300. this.renderItems = [];
  18301. /**
  18302. * The current render items index.
  18303. *
  18304. * @type {Number}
  18305. * @default 0
  18306. */
  18307. this.renderItemsIndex = 0;
  18308. /**
  18309. * A list with opaque render items.
  18310. *
  18311. * @type {Array<Object>}
  18312. */
  18313. this.opaque = [];
  18314. /**
  18315. * A list with transparent render items which require
  18316. * double pass rendering (e.g. transmissive objects).
  18317. *
  18318. * @type {Array<Object>}
  18319. */
  18320. this.transparentDoublePass = [];
  18321. /**
  18322. * A list with transparent render items.
  18323. *
  18324. * @type {Array<Object>}
  18325. */
  18326. this.transparent = [];
  18327. /**
  18328. * A list with transparent render bundle data.
  18329. *
  18330. * @type {Array<Object>}
  18331. */
  18332. this.bundles = [];
  18333. /**
  18334. * The render list's lights node. This node is later
  18335. * relevant for the actual analytical light nodes which
  18336. * compute the scene's lighting in the shader.
  18337. *
  18338. * @type {LightsNode}
  18339. */
  18340. this.lightsNode = lighting.getNode( scene, camera );
  18341. /**
  18342. * The scene's lights stored in an array. This array
  18343. * is used to setup the lights node.
  18344. *
  18345. * @type {Array<Light>}
  18346. */
  18347. this.lightsArray = [];
  18348. /**
  18349. * The scene.
  18350. *
  18351. * @type {Scene}
  18352. */
  18353. this.scene = scene;
  18354. /**
  18355. * The camera the scene is rendered with.
  18356. *
  18357. * @type {Camera}
  18358. */
  18359. this.camera = camera;
  18360. /**
  18361. * How many objects perform occlusion query tests.
  18362. *
  18363. * @type {Number}
  18364. * @default 0
  18365. */
  18366. this.occlusionQueryCount = 0;
  18367. }
  18368. /**
  18369. * This method is called right at the beginning of a render call
  18370. * before the scene is analyzed. It prepares the internal data
  18371. * structures for the upcoming render lists generation.
  18372. *
  18373. * @return {RenderList} A reference to this render list.
  18374. */
  18375. begin() {
  18376. this.renderItemsIndex = 0;
  18377. this.opaque.length = 0;
  18378. this.transparentDoublePass.length = 0;
  18379. this.transparent.length = 0;
  18380. this.bundles.length = 0;
  18381. this.lightsArray.length = 0;
  18382. this.occlusionQueryCount = 0;
  18383. return this;
  18384. }
  18385. /**
  18386. * Returns a render item for the giving render item state. The state is defined
  18387. * by a series of object-related parameters.
  18388. *
  18389. * The method avoids object creation by holding render items and reusing them in
  18390. * subsequent render calls (just with different property values).
  18391. *
  18392. * @param {Object3D} object - The 3D object.
  18393. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18394. * @param {Material} material - The 3D object's material.
  18395. * @param {Number} groupOrder - The current group order.
  18396. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18397. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18398. * @param {ClippingContext} clippingContext - The current clipping context.
  18399. * @return {Object} The render item.
  18400. */
  18401. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18402. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18403. if ( renderItem === undefined ) {
  18404. renderItem = {
  18405. id: object.id,
  18406. object: object,
  18407. geometry: geometry,
  18408. material: material,
  18409. groupOrder: groupOrder,
  18410. renderOrder: object.renderOrder,
  18411. z: z,
  18412. group: group,
  18413. clippingContext: clippingContext
  18414. };
  18415. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18416. } else {
  18417. renderItem.id = object.id;
  18418. renderItem.object = object;
  18419. renderItem.geometry = geometry;
  18420. renderItem.material = material;
  18421. renderItem.groupOrder = groupOrder;
  18422. renderItem.renderOrder = object.renderOrder;
  18423. renderItem.z = z;
  18424. renderItem.group = group;
  18425. renderItem.clippingContext = clippingContext;
  18426. }
  18427. this.renderItemsIndex ++;
  18428. return renderItem;
  18429. }
  18430. /**
  18431. * Pushes the given object as a render item to the internal render lists.
  18432. * The selected lists depend on the object properties.
  18433. *
  18434. * @param {Object3D} object - The 3D object.
  18435. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18436. * @param {Material} material - The 3D object's material.
  18437. * @param {Number} groupOrder - The current group order.
  18438. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18439. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18440. * @param {ClippingContext} clippingContext - The current clipping context.
  18441. */
  18442. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18443. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18444. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18445. if ( material.transparent === true || material.transmission > 0 ) {
  18446. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18447. this.transparent.push( renderItem );
  18448. } else {
  18449. this.opaque.push( renderItem );
  18450. }
  18451. }
  18452. /**
  18453. * Inserts the given object as a render item at the start of the internal render lists.
  18454. * The selected lists depend on the object properties.
  18455. *
  18456. * @param {Object3D} object - The 3D object.
  18457. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18458. * @param {Material} material - The 3D object's material.
  18459. * @param {Number} groupOrder - The current group order.
  18460. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18461. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18462. * @param {ClippingContext} clippingContext - The current clipping context.
  18463. */
  18464. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18465. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18466. if ( material.transparent === true || material.transmission > 0 ) {
  18467. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18468. this.transparent.unshift( renderItem );
  18469. } else {
  18470. this.opaque.unshift( renderItem );
  18471. }
  18472. }
  18473. /**
  18474. * Pushes render bundle group data into the render list.
  18475. *
  18476. * @param {Object} group - Bundle group data.
  18477. */
  18478. pushBundle( group ) {
  18479. this.bundles.push( group );
  18480. }
  18481. /**
  18482. * Pushes a light into the render list.
  18483. *
  18484. * @param {Light} light - The light.
  18485. */
  18486. pushLight( light ) {
  18487. this.lightsArray.push( light );
  18488. }
  18489. /**
  18490. * Sorts the internal render lists.
  18491. *
  18492. * @param {function(Any, Any): Number} customOpaqueSort - A custom sort function for opaque objects.
  18493. * @param {function(Any, Any): Number} customTransparentSort - A custom sort function for transparent objects.
  18494. */
  18495. sort( customOpaqueSort, customTransparentSort ) {
  18496. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18497. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18498. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18499. }
  18500. /**
  18501. * This method performs finalizing tasks right after the render lists
  18502. * have been generated.
  18503. */
  18504. finish() {
  18505. // update lights
  18506. this.lightsNode.setLights( this.lightsArray );
  18507. // Clear references from inactive renderItems in the list
  18508. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18509. const renderItem = this.renderItems[ i ];
  18510. if ( renderItem.id === null ) break;
  18511. renderItem.id = null;
  18512. renderItem.object = null;
  18513. renderItem.geometry = null;
  18514. renderItem.material = null;
  18515. renderItem.groupOrder = null;
  18516. renderItem.renderOrder = null;
  18517. renderItem.z = null;
  18518. renderItem.group = null;
  18519. renderItem.clippingContext = null;
  18520. }
  18521. }
  18522. }
  18523. const _chainKeys$4 = [];
  18524. /**
  18525. * This renderer module manages the render lists which are unique
  18526. * per scene and camera combination.
  18527. *
  18528. * @private
  18529. */
  18530. class RenderLists {
  18531. /**
  18532. * Constructs a render lists management component.
  18533. *
  18534. * @param {Lighting} lighting - The lighting management component.
  18535. */
  18536. constructor( lighting ) {
  18537. /**
  18538. * The lighting management component.
  18539. *
  18540. * @type {Lighting}
  18541. */
  18542. this.lighting = lighting;
  18543. /**
  18544. * The internal chain map which holds the render lists.
  18545. *
  18546. * @type {ChainMap}
  18547. */
  18548. this.lists = new ChainMap();
  18549. }
  18550. /**
  18551. * Returns a render list for the given scene and camera.
  18552. *
  18553. * @param {Scene} scene - The scene.
  18554. * @param {Camera} camera - The camera.
  18555. * @return {RenderList} The render list.
  18556. */
  18557. get( scene, camera ) {
  18558. const lists = this.lists;
  18559. _chainKeys$4[ 0 ] = scene;
  18560. _chainKeys$4[ 1 ] = camera;
  18561. let list = lists.get( _chainKeys$4 );
  18562. if ( list === undefined ) {
  18563. list = new RenderList( this.lighting, scene, camera );
  18564. lists.set( _chainKeys$4, list );
  18565. }
  18566. _chainKeys$4.length = 0;
  18567. return list;
  18568. }
  18569. /**
  18570. * Frees all internal resources.
  18571. */
  18572. dispose() {
  18573. this.lists = new ChainMap();
  18574. }
  18575. }
  18576. let _id$7 = 0;
  18577. /**
  18578. * Any render or compute command is executed in a specific context that defines
  18579. * the state of the renderer and its backend. Typical examples for such context
  18580. * data are the current clear values or data from the active framebuffer. This
  18581. * module is used to represent these contexts as objects.
  18582. *
  18583. * @private
  18584. */
  18585. class RenderContext {
  18586. /**
  18587. * Constructs a new render context.
  18588. */
  18589. constructor() {
  18590. /**
  18591. * The context's ID.
  18592. *
  18593. * @type {Number}
  18594. */
  18595. this.id = _id$7 ++;
  18596. /**
  18597. * Whether the current active framebuffer has a color attachment.
  18598. *
  18599. * @type {Boolean}
  18600. * @default true
  18601. */
  18602. this.color = true;
  18603. /**
  18604. * Whether the color attachment should be cleared or not.
  18605. *
  18606. * @type {Boolean}
  18607. * @default true
  18608. */
  18609. this.clearColor = true;
  18610. /**
  18611. * The clear color value.
  18612. *
  18613. * @type {Object}
  18614. * @default true
  18615. */
  18616. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18617. /**
  18618. * Whether the current active framebuffer has a depth attachment.
  18619. *
  18620. * @type {Boolean}
  18621. * @default true
  18622. */
  18623. this.depth = true;
  18624. /**
  18625. * Whether the depth attachment should be cleared or not.
  18626. *
  18627. * @type {Boolean}
  18628. * @default true
  18629. */
  18630. this.clearDepth = true;
  18631. /**
  18632. * The clear depth value.
  18633. *
  18634. * @type {Number}
  18635. * @default 1
  18636. */
  18637. this.clearDepthValue = 1;
  18638. /**
  18639. * Whether the current active framebuffer has a stencil attachment.
  18640. *
  18641. * @type {Boolean}
  18642. * @default false
  18643. */
  18644. this.stencil = false;
  18645. /**
  18646. * Whether the stencil attachment should be cleared or not.
  18647. *
  18648. * @type {Boolean}
  18649. * @default true
  18650. */
  18651. this.clearStencil = true;
  18652. /**
  18653. * The clear stencil value.
  18654. *
  18655. * @type {Number}
  18656. * @default 1
  18657. */
  18658. this.clearStencilValue = 1;
  18659. /**
  18660. * By default the viewport encloses the entire framebuffer If a smaller
  18661. * viewport is manually defined, this property is to `true` by the renderer.
  18662. *
  18663. * @type {Boolean}
  18664. * @default false
  18665. */
  18666. this.viewport = false;
  18667. /**
  18668. * The viewport value. This value is in physical pixels meaning it incorporates
  18669. * the renderer's pixel ratio. The viewport property of render targets or
  18670. * the renderer is in logical pixels.
  18671. *
  18672. * @type {Vector4}
  18673. */
  18674. this.viewportValue = new Vector4();
  18675. /**
  18676. * When the scissor test is active and scissor rectangle smaller than the
  18677. * framebuffers dimensions, this property is to `true` by the renderer.
  18678. *
  18679. * @type {Boolean}
  18680. * @default false
  18681. */
  18682. this.scissor = false;
  18683. /**
  18684. * The scissor rectangle.
  18685. *
  18686. * @type {Vector4}
  18687. */
  18688. this.scissorValue = new Vector4();
  18689. /**
  18690. * The active render target.
  18691. *
  18692. * @type {RenderTarget?}
  18693. * @default null
  18694. */
  18695. this.renderTarget = null;
  18696. /**
  18697. * The textures of the active render target.
  18698. * `null` when no render target is set.
  18699. *
  18700. * @type {Array<Texture>?}
  18701. * @default null
  18702. */
  18703. this.textures = null;
  18704. /**
  18705. * The depth texture of the active render target.
  18706. * `null` when no render target is set.
  18707. *
  18708. * @type {DepthTexture?}
  18709. * @default null
  18710. */
  18711. this.depthTexture = null;
  18712. /**
  18713. * The active cube face.
  18714. *
  18715. * @type {Number}
  18716. * @default 0
  18717. */
  18718. this.activeCubeFace = 0;
  18719. /**
  18720. * The active mipmap level.
  18721. *
  18722. * @type {Number}
  18723. * @default 0
  18724. */
  18725. this.activeMipmapLevel = 0;
  18726. /**
  18727. * The number of MSAA samples. This value is always `1` when
  18728. * MSAA isn't used.
  18729. *
  18730. * @type {Number}
  18731. * @default 1
  18732. */
  18733. this.sampleCount = 1;
  18734. /**
  18735. * The active render target's width in physical pixels.
  18736. *
  18737. * @type {Number}
  18738. * @default 0
  18739. */
  18740. this.width = 0;
  18741. /**
  18742. * The active render target's height in physical pixels.
  18743. *
  18744. * @type {Number}
  18745. * @default 0
  18746. */
  18747. this.height = 0;
  18748. /**
  18749. * The occlusion query count.
  18750. *
  18751. * @type {Number}
  18752. * @default 0
  18753. */
  18754. this.occlusionQueryCount = 0;
  18755. /**
  18756. * The current clipping context.
  18757. *
  18758. * @type {ClippingContext?}
  18759. * @default null
  18760. */
  18761. this.clippingContext = null;
  18762. /**
  18763. * This flag can be used for type testing.
  18764. *
  18765. * @type {Boolean}
  18766. * @readonly
  18767. * @default true
  18768. */
  18769. this.isRenderContext = true;
  18770. }
  18771. /**
  18772. * Returns the cache key of this render context.
  18773. *
  18774. * @return {Number} The cache key.
  18775. */
  18776. getCacheKey() {
  18777. return getCacheKey( this );
  18778. }
  18779. }
  18780. /**
  18781. * Computes a cache key for the given render context. This key
  18782. * should identify the render target state so it is possible to
  18783. * configure the correct attachments in the respective backend.
  18784. *
  18785. * @param {RenderContext} renderContext - The render context.
  18786. * @return {Number} The cache key.
  18787. */
  18788. function getCacheKey( renderContext ) {
  18789. const { textures, activeCubeFace } = renderContext;
  18790. const values = [ activeCubeFace ];
  18791. for ( const texture of textures ) {
  18792. values.push( texture.id );
  18793. }
  18794. return hashArray( values );
  18795. }
  18796. const _chainKeys$3 = [];
  18797. const _defaultScene = /*@__PURE__*/ new Scene();
  18798. const _defaultCamera = /*@__PURE__*/ new Camera();
  18799. /**
  18800. * This module manages the render contexts of the renderer.
  18801. *
  18802. * @private
  18803. */
  18804. class RenderContexts {
  18805. /**
  18806. * Constructs a new render context management component.
  18807. */
  18808. constructor() {
  18809. /**
  18810. * A dictionary that manages render contexts in chain maps
  18811. * for each attachment state.
  18812. *
  18813. * @type {Object<String,ChainMap>}
  18814. */
  18815. this.chainMaps = {};
  18816. }
  18817. /**
  18818. * Returns a render context for the given scene, camera and render target.
  18819. *
  18820. * @param {Scene} scene - The scene.
  18821. * @param {Camera} camera - The camera that is used to render the scene.
  18822. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18823. * @return {RenderContext} The render context.
  18824. */
  18825. get( scene, camera, renderTarget = null ) {
  18826. _chainKeys$3[ 0 ] = scene;
  18827. _chainKeys$3[ 1 ] = camera;
  18828. let attachmentState;
  18829. if ( renderTarget === null ) {
  18830. attachmentState = 'default';
  18831. } else {
  18832. const format = renderTarget.texture.format;
  18833. const count = renderTarget.textures.length;
  18834. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18835. }
  18836. const chainMap = this._getChainMap( attachmentState );
  18837. let renderState = chainMap.get( _chainKeys$3 );
  18838. if ( renderState === undefined ) {
  18839. renderState = new RenderContext();
  18840. chainMap.set( _chainKeys$3, renderState );
  18841. }
  18842. _chainKeys$3.length = 0;
  18843. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18844. return renderState;
  18845. }
  18846. /**
  18847. * Returns a render context intended for clear operations.
  18848. *
  18849. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18850. * @return {RenderContext} The render context.
  18851. */
  18852. getForClear( renderTarget = null ) {
  18853. return this.get( _defaultScene, _defaultCamera, renderTarget );
  18854. }
  18855. /**
  18856. * Returns a chain map for the given attachment state.
  18857. *
  18858. * @private
  18859. * @param {String} attachmentState - The attachment state.
  18860. * @return {ChainMap} The chain map.
  18861. */
  18862. _getChainMap( attachmentState ) {
  18863. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18864. }
  18865. /**
  18866. * Frees internal resources.
  18867. */
  18868. dispose() {
  18869. this.chainMaps = {};
  18870. }
  18871. }
  18872. const _size$3 = /*@__PURE__*/ new Vector3();
  18873. /**
  18874. * This module manages the textures of the renderer.
  18875. *
  18876. * @private
  18877. * @augments DataMap
  18878. */
  18879. class Textures extends DataMap {
  18880. /**
  18881. * Constructs a new texture management component.
  18882. *
  18883. * @param {Renderer} renderer - The renderer.
  18884. * @param {Backend} backend - The renderer's backend.
  18885. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18886. */
  18887. constructor( renderer, backend, info ) {
  18888. super();
  18889. /**
  18890. * The renderer.
  18891. *
  18892. * @type {Renderer}
  18893. */
  18894. this.renderer = renderer;
  18895. /**
  18896. * The backend.
  18897. *
  18898. * @type {Backend}
  18899. */
  18900. this.backend = backend;
  18901. /**
  18902. * Renderer component for managing metrics and monitoring data.
  18903. *
  18904. * @type {Info}
  18905. */
  18906. this.info = info;
  18907. }
  18908. /**
  18909. * Updates the given render target. Based on the given render target configuration,
  18910. * it updates the texture states representing the attachments of the framebuffer.
  18911. *
  18912. * @param {RenderTarget} renderTarget - The render target to update.
  18913. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18914. */
  18915. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18916. const renderTargetData = this.get( renderTarget );
  18917. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18918. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18919. const textures = renderTarget.textures;
  18920. const size = this.getSize( textures[ 0 ] );
  18921. const mipWidth = size.width >> activeMipmapLevel;
  18922. const mipHeight = size.height >> activeMipmapLevel;
  18923. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18924. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18925. let textureNeedsUpdate = false;
  18926. if ( depthTexture === undefined && useDepthTexture ) {
  18927. depthTexture = new DepthTexture();
  18928. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18929. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18930. depthTexture.image.width = mipWidth;
  18931. depthTexture.image.height = mipHeight;
  18932. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18933. }
  18934. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18935. textureNeedsUpdate = true;
  18936. if ( depthTexture ) {
  18937. depthTexture.needsUpdate = true;
  18938. depthTexture.image.width = mipWidth;
  18939. depthTexture.image.height = mipHeight;
  18940. }
  18941. }
  18942. renderTargetData.width = size.width;
  18943. renderTargetData.height = size.height;
  18944. renderTargetData.textures = textures;
  18945. renderTargetData.depthTexture = depthTexture || null;
  18946. renderTargetData.depth = renderTarget.depthBuffer;
  18947. renderTargetData.stencil = renderTarget.stencilBuffer;
  18948. renderTargetData.renderTarget = renderTarget;
  18949. if ( renderTargetData.sampleCount !== sampleCount ) {
  18950. textureNeedsUpdate = true;
  18951. if ( depthTexture ) {
  18952. depthTexture.needsUpdate = true;
  18953. }
  18954. renderTargetData.sampleCount = sampleCount;
  18955. }
  18956. //
  18957. const options = { sampleCount };
  18958. // XR render targets require no texture updates
  18959. if ( renderTarget.isXRRenderTarget !== true ) {
  18960. for ( let i = 0; i < textures.length; i ++ ) {
  18961. const texture = textures[ i ];
  18962. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18963. this.updateTexture( texture, options );
  18964. }
  18965. if ( depthTexture ) {
  18966. this.updateTexture( depthTexture, options );
  18967. }
  18968. }
  18969. // dispose handler
  18970. if ( renderTargetData.initialized !== true ) {
  18971. renderTargetData.initialized = true;
  18972. // dispose
  18973. const onDispose = () => {
  18974. renderTarget.removeEventListener( 'dispose', onDispose );
  18975. for ( let i = 0; i < textures.length; i ++ ) {
  18976. this._destroyTexture( textures[ i ] );
  18977. }
  18978. if ( depthTexture ) {
  18979. this._destroyTexture( depthTexture );
  18980. }
  18981. this.delete( renderTarget );
  18982. };
  18983. renderTarget.addEventListener( 'dispose', onDispose );
  18984. }
  18985. }
  18986. /**
  18987. * Updates the given texture. Depending on the texture state, this method
  18988. * triggers the upload of texture data to the GPU memory. If the texture data are
  18989. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18990. *
  18991. * @param {Texture} texture - The texture to update.
  18992. * @param {Object} [options={}] - The options.
  18993. */
  18994. updateTexture( texture, options = {} ) {
  18995. const textureData = this.get( texture );
  18996. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18997. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18998. const backend = this.backend;
  18999. if ( isRenderTarget && textureData.initialized === true ) {
  19000. // it's an update
  19001. backend.destroySampler( texture );
  19002. backend.destroyTexture( texture );
  19003. }
  19004. //
  19005. if ( texture.isFramebufferTexture ) {
  19006. const renderTarget = this.renderer.getRenderTarget();
  19007. if ( renderTarget ) {
  19008. texture.type = renderTarget.texture.type;
  19009. } else {
  19010. texture.type = UnsignedByteType;
  19011. }
  19012. }
  19013. //
  19014. const { width, height, depth } = this.getSize( texture );
  19015. options.width = width;
  19016. options.height = height;
  19017. options.depth = depth;
  19018. options.needsMipmaps = this.needsMipmaps( texture );
  19019. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  19020. //
  19021. if ( isRenderTarget || texture.isStorageTexture === true ) {
  19022. backend.createSampler( texture );
  19023. backend.createTexture( texture, options );
  19024. textureData.generation = texture.version;
  19025. } else {
  19026. const needsCreate = textureData.initialized !== true;
  19027. if ( needsCreate ) backend.createSampler( texture );
  19028. if ( texture.version > 0 ) {
  19029. const image = texture.image;
  19030. if ( image === undefined ) {
  19031. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  19032. } else if ( image.complete === false ) {
  19033. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  19034. } else {
  19035. if ( texture.images ) {
  19036. const images = [];
  19037. for ( const image of texture.images ) {
  19038. images.push( image );
  19039. }
  19040. options.images = images;
  19041. } else {
  19042. options.image = image;
  19043. }
  19044. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  19045. backend.createTexture( texture, options );
  19046. textureData.isDefaultTexture = false;
  19047. textureData.generation = texture.version;
  19048. }
  19049. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  19050. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  19051. }
  19052. } else {
  19053. // async update
  19054. backend.createDefaultTexture( texture );
  19055. textureData.isDefaultTexture = true;
  19056. textureData.generation = texture.version;
  19057. }
  19058. }
  19059. // dispose handler
  19060. if ( textureData.initialized !== true ) {
  19061. textureData.initialized = true;
  19062. textureData.generation = texture.version;
  19063. //
  19064. this.info.memory.textures ++;
  19065. // dispose
  19066. const onDispose = () => {
  19067. texture.removeEventListener( 'dispose', onDispose );
  19068. this._destroyTexture( texture );
  19069. this.info.memory.textures --;
  19070. };
  19071. texture.addEventListener( 'dispose', onDispose );
  19072. }
  19073. //
  19074. textureData.version = texture.version;
  19075. }
  19076. /**
  19077. * Computes the size of the given texture and writes the result
  19078. * into the target vector. This vector is also returned by the
  19079. * method.
  19080. *
  19081. * If no texture data are available for the compute yet, the method
  19082. * returns default size values.
  19083. *
  19084. * @param {Texture} texture - The texture to compute the size for.
  19085. * @param {Vector3} target - The target vector.
  19086. * @return {Vector3} The target vector.
  19087. */
  19088. getSize( texture, target = _size$3 ) {
  19089. let image = texture.images ? texture.images[ 0 ] : texture.image;
  19090. if ( image ) {
  19091. if ( image.image !== undefined ) image = image.image;
  19092. target.width = image.width || 1;
  19093. target.height = image.height || 1;
  19094. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  19095. } else {
  19096. target.width = target.height = target.depth = 1;
  19097. }
  19098. return target;
  19099. }
  19100. /**
  19101. * Computes the number of mipmap levels for the given texture.
  19102. *
  19103. * @param {Texture} texture - The texture.
  19104. * @param {Number} width - The texture's width.
  19105. * @param {Number} height - The texture's height.
  19106. * @return {Number} The number of mipmap levels.
  19107. */
  19108. getMipLevels( texture, width, height ) {
  19109. let mipLevelCount;
  19110. if ( texture.isCompressedTexture ) {
  19111. if ( texture.mipmaps ) {
  19112. mipLevelCount = texture.mipmaps.length;
  19113. } else {
  19114. mipLevelCount = 1;
  19115. }
  19116. } else {
  19117. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  19118. }
  19119. return mipLevelCount;
  19120. }
  19121. /**
  19122. * Returns `true` if the given texture requires mipmaps.
  19123. *
  19124. * @param {Texture} texture - The texture.
  19125. * @return {Boolean} Whether mipmaps are required or not.
  19126. */
  19127. needsMipmaps( texture ) {
  19128. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  19129. }
  19130. /**
  19131. * Returns `true` if the given texture is an environment map.
  19132. *
  19133. * @param {Texture} texture - The texture.
  19134. * @return {Boolean} Whether the given texture is an environment map or not.
  19135. */
  19136. isEnvironmentTexture( texture ) {
  19137. const mapping = texture.mapping;
  19138. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  19139. }
  19140. /**
  19141. * Frees internal resource when the given texture isn't
  19142. * required anymore.
  19143. *
  19144. * @param {Texture} texture - The texture to destroy.
  19145. */
  19146. _destroyTexture( texture ) {
  19147. this.backend.destroySampler( texture );
  19148. this.backend.destroyTexture( texture );
  19149. this.delete( texture );
  19150. }
  19151. }
  19152. /**
  19153. * A four-component version of {@link Color} which is internally
  19154. * used by the renderer to represents clear color with alpha as
  19155. * one object.
  19156. *
  19157. * @private
  19158. * @augments Color
  19159. */
  19160. class Color4 extends Color {
  19161. /**
  19162. * Constructs a new four-component color.
  19163. * You can also pass a single THREE.Color, hex or
  19164. * string argument to this constructor.
  19165. *
  19166. * @param {Number|String} [r=1] - The red value.
  19167. * @param {Number} [g=1] - The green value.
  19168. * @param {Number} [b=1] - The blue value.
  19169. * @param {Number} [a=1] - The alpha value.
  19170. */
  19171. constructor( r, g, b, a = 1 ) {
  19172. super( r, g, b );
  19173. this.a = a;
  19174. }
  19175. /**
  19176. * Overwrites the default to honor alpha.
  19177. * You can also pass a single THREE.Color, hex or
  19178. * string argument to this method.
  19179. *
  19180. * @param {Number|String} r - The red value.
  19181. * @param {Number} g - The green value.
  19182. * @param {Number} b - The blue value.
  19183. * @param {Number} [a=1] - The alpha value.
  19184. * @return {Color4} A reference to this object.
  19185. */
  19186. set( r, g, b, a = 1 ) {
  19187. this.a = a;
  19188. return super.set( r, g, b );
  19189. }
  19190. /**
  19191. * Overwrites the default to honor alpha.
  19192. *
  19193. * @param {Color4} color - The color to copy.
  19194. * @return {Color4} A reference to this object.
  19195. */
  19196. copy( color ) {
  19197. if ( color.a !== undefined ) this.a = color.a;
  19198. return super.copy( color );
  19199. }
  19200. /**
  19201. * Overwrites the default to honor alpha.
  19202. *
  19203. * @return {Color4} The cloned color.
  19204. */
  19205. clone() {
  19206. return new this.constructor( this.r, this.g, this.b, this.a );
  19207. }
  19208. }
  19209. /** @module ParameterNode **/
  19210. /**
  19211. * Special version of {@link PropertyNode} which is used for parameters.
  19212. *
  19213. * @augments PropertyNode
  19214. */
  19215. class ParameterNode extends PropertyNode {
  19216. static get type() {
  19217. return 'ParameterNode';
  19218. }
  19219. /**
  19220. * Constructs a new parameter node.
  19221. *
  19222. * @param {String} nodeType - The type of the node.
  19223. * @param {String?} [name=null] - The name of the parameter in the shader.
  19224. */
  19225. constructor( nodeType, name = null ) {
  19226. super( nodeType, name );
  19227. /**
  19228. * This flag can be used for type testing.
  19229. *
  19230. * @type {Boolean}
  19231. * @readonly
  19232. * @default true
  19233. */
  19234. this.isParameterNode = true;
  19235. }
  19236. getHash() {
  19237. return this.uuid;
  19238. }
  19239. generate() {
  19240. return this.name;
  19241. }
  19242. }
  19243. /**
  19244. * TSL function for creating a parameter node.
  19245. *
  19246. * @function
  19247. * @param {String} type - The type of the node.
  19248. * @param {String?} name - The name of the parameter in the shader.
  19249. * @returns {ParameterNode}
  19250. */
  19251. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  19252. /** @module StackNode **/
  19253. /**
  19254. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  19255. * They are usually needed in cases like `If`, `Else`.
  19256. *
  19257. * @augments Node
  19258. */
  19259. class StackNode extends Node {
  19260. static get type() {
  19261. return 'StackNode';
  19262. }
  19263. /**
  19264. * Constructs a new stack node.
  19265. *
  19266. * @param {StackNode?} [parent=null] - The parent stack node.
  19267. */
  19268. constructor( parent = null ) {
  19269. super();
  19270. /**
  19271. * List of nodes.
  19272. *
  19273. * @type {Array<Node>}
  19274. */
  19275. this.nodes = [];
  19276. /**
  19277. * The output node.
  19278. *
  19279. * @type {Node?}
  19280. * @default null
  19281. */
  19282. this.outputNode = null;
  19283. /**
  19284. * The parent stack node.
  19285. *
  19286. * @type {StackNode}
  19287. * @default null
  19288. */
  19289. this.parent = parent;
  19290. /**
  19291. * The current conditional node.
  19292. *
  19293. * @private
  19294. * @type {ConditionalNode}
  19295. * @default null
  19296. */
  19297. this._currentCond = null;
  19298. /**
  19299. * This flag can be used for type testing.
  19300. *
  19301. * @type {Boolean}
  19302. * @readonly
  19303. * @default true
  19304. */
  19305. this.isStackNode = true;
  19306. }
  19307. getNodeType( builder ) {
  19308. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  19309. }
  19310. getMemberType( builder, name ) {
  19311. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  19312. }
  19313. /**
  19314. * Adds a node to this stack.
  19315. *
  19316. * @param {Node} node - The node to add.
  19317. * @return {StackNode} A reference to this stack node.
  19318. */
  19319. add( node ) {
  19320. this.nodes.push( node );
  19321. return this;
  19322. }
  19323. /**
  19324. * Represent an `if` statement in TSL.
  19325. *
  19326. * @param {Node} boolNode - Represents the condition.
  19327. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19328. * @return {StackNode} A reference to this stack node.
  19329. */
  19330. If( boolNode, method ) {
  19331. const methodNode = new ShaderNode( method );
  19332. this._currentCond = select( boolNode, methodNode );
  19333. return this.add( this._currentCond );
  19334. }
  19335. /**
  19336. * Represent an `elseif` statement in TSL.
  19337. *
  19338. * @param {Node} boolNode - Represents the condition.
  19339. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19340. * @return {StackNode} A reference to this stack node.
  19341. */
  19342. ElseIf( boolNode, method ) {
  19343. const methodNode = new ShaderNode( method );
  19344. const ifNode = select( boolNode, methodNode );
  19345. this._currentCond.elseNode = ifNode;
  19346. this._currentCond = ifNode;
  19347. return this;
  19348. }
  19349. /**
  19350. * Represent an `else` statement in TSL.
  19351. *
  19352. * @param {Function} method - TSL code which is executed in the `else` case.
  19353. * @return {StackNode} A reference to this stack node.
  19354. */
  19355. Else( method ) {
  19356. this._currentCond.elseNode = new ShaderNode( method );
  19357. return this;
  19358. }
  19359. build( builder, ...params ) {
  19360. const previousStack = getCurrentStack();
  19361. setCurrentStack( this );
  19362. for ( const node of this.nodes ) {
  19363. node.build( builder, 'void' );
  19364. }
  19365. setCurrentStack( previousStack );
  19366. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19367. }
  19368. // Deprecated
  19369. /**
  19370. * @function
  19371. * @deprecated since r168. Use {@link StackNode#Else} instead.
  19372. *
  19373. * @param {...any} params
  19374. * @returns {StackNode}
  19375. */
  19376. else( ...params ) { // @deprecated, r168
  19377. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19378. return this.Else( ...params );
  19379. }
  19380. /**
  19381. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  19382. *
  19383. * @param {...any} params
  19384. * @returns {StackNode}
  19385. */
  19386. elseif( ...params ) { // @deprecated, r168
  19387. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19388. return this.ElseIf( ...params );
  19389. }
  19390. }
  19391. /**
  19392. * TSL function for creating a stack node.
  19393. *
  19394. * @function
  19395. * @param {StackNode?} [parent=null] - The parent stack node.
  19396. * @returns {StackNode}
  19397. */
  19398. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19399. /** @module StructTypeNode **/
  19400. /**
  19401. * Generates a layout for struct members.
  19402. * This function takes an object representing struct members and returns an array of member layouts.
  19403. * Each member layout includes the member's name, type, and whether it is atomic.
  19404. *
  19405. * @param {Object.<string, string|Object>} members - An object where keys are member names and values are either types (as strings) or objects with type and atomic properties.
  19406. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  19407. */
  19408. function getMembersLayout( members ) {
  19409. return Object.entries( members ).map( ( [ name, value ] ) => {
  19410. if ( typeof value === 'string' ) {
  19411. return { name, type: value, atomic: false };
  19412. }
  19413. return { name, type: value.type, atomic: value.atomic || false };
  19414. } );
  19415. }
  19416. /**
  19417. * Represents a struct type node in the node-based system.
  19418. * This class is used to define and manage the layout and types of struct members.
  19419. * It extends the base Node class and provides methods to get the length of the struct,
  19420. * retrieve member types, and generate the struct type for a builder.
  19421. *
  19422. * @augments Node
  19423. */
  19424. class StructTypeNode extends Node {
  19425. static get type() {
  19426. return 'StructTypeNode';
  19427. }
  19428. /**
  19429. * Creates an instance of StructTypeNode.
  19430. *
  19431. * @param {Object} membersLayout - The layout of the members for the struct.
  19432. * @param {string} [name=null] - The optional name of the struct.
  19433. */
  19434. constructor( membersLayout, name = null ) {
  19435. super( 'struct' );
  19436. /**
  19437. * The layout of the members for the struct
  19438. *
  19439. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  19440. */
  19441. this.membersLayout = getMembersLayout( membersLayout );
  19442. /**
  19443. * The name of the struct.
  19444. *
  19445. * @type {String}
  19446. * @default null
  19447. */
  19448. this.name = name;
  19449. /**
  19450. * This flag can be used for type testing.
  19451. *
  19452. * @type {Boolean}
  19453. * @readonly
  19454. * @default true
  19455. */
  19456. this.isStructLayoutNode = true;
  19457. }
  19458. /**
  19459. * Returns the length of the struct.
  19460. * The length is calculated by summing the lengths of the struct's members.
  19461. *
  19462. * @returns {Number} The length of the struct.
  19463. */
  19464. getLength() {
  19465. let length = 0;
  19466. for ( const member of this.membersLayout ) {
  19467. length += getLengthFromType( member.type );
  19468. }
  19469. return length;
  19470. }
  19471. getMemberType( builder, name ) {
  19472. const member = this.membersLayout.find( m => m.name === name );
  19473. return member ? member.type : 'void';
  19474. }
  19475. getNodeType( builder ) {
  19476. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  19477. return structType.name;
  19478. }
  19479. generate( builder ) {
  19480. return this.getNodeType( builder );
  19481. }
  19482. }
  19483. /** @module StructNode **/
  19484. /**
  19485. * StructNode allows to create custom structures with multiple members.
  19486. * This can also be used to define structures in attribute and uniform data.
  19487. *
  19488. * ```js
  19489. * // Define a custom struct
  19490. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  19491. *
  19492. * // Create a new instance of the struct
  19493. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  19494. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  19495. *
  19496. * // Access the struct members
  19497. * const min = bb.get( 'min' );
  19498. *
  19499. * // Assign a new value to a member
  19500. * min.assign( vec3() );
  19501. * ```
  19502. * @augments Node
  19503. */
  19504. class StructNode extends Node {
  19505. static get type() {
  19506. return 'StructNode';
  19507. }
  19508. constructor( structLayoutNode, values ) {
  19509. super( 'vec3' );
  19510. this.structLayoutNode = structLayoutNode;
  19511. this.values = values;
  19512. this.isStructNode = true;
  19513. }
  19514. getNodeType( builder ) {
  19515. return this.structLayoutNode.getNodeType( builder );
  19516. }
  19517. getMemberType( builder, name ) {
  19518. return this.structLayoutNode.getMemberType( builder, name );
  19519. }
  19520. generate( builder ) {
  19521. const nodeVar = builder.getVarFromNode( this );
  19522. const structType = nodeVar.type;
  19523. const propertyName = builder.getPropertyName( nodeVar );
  19524. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  19525. return nodeVar.name;
  19526. }
  19527. }
  19528. /**
  19529. * TSL function for creating a struct node.
  19530. *
  19531. * @function
  19532. * @param {Object} membersLayout - The layout of the struct members.
  19533. * @param {string} [name=null] - The name of the struct.
  19534. * @returns {Function} The struct function.
  19535. */
  19536. const struct = ( membersLayout, name = null ) => {
  19537. const structLayout = new StructTypeNode( membersLayout, name );
  19538. const struct = ( ...params ) => {
  19539. let values = null;
  19540. if ( params.length > 0 ) {
  19541. if ( params[ 0 ].isNode ) {
  19542. values = {};
  19543. const names = Object.keys( membersLayout );
  19544. for ( let i = 0; i < params.length; i ++ ) {
  19545. values[ names[ i ] ] = params[ i ];
  19546. }
  19547. } else {
  19548. values = params[ 0 ];
  19549. }
  19550. }
  19551. return nodeObject( new StructNode( structLayout, values ) );
  19552. };
  19553. struct.layout = structLayout;
  19554. struct.isStruct = true;
  19555. return struct;
  19556. };
  19557. /** @module OutputStructNode **/
  19558. /**
  19559. * This node can be used to define multiple outputs in a shader programs.
  19560. *
  19561. * @augments Node
  19562. */
  19563. class OutputStructNode extends Node {
  19564. static get type() {
  19565. return 'OutputStructNode';
  19566. }
  19567. /**
  19568. * Constructs a new output struct node. The constructor can be invoked with an
  19569. * arbitrary number of nodes representing the members.
  19570. *
  19571. * @param {...Node} members - A parameter list of nodes.
  19572. */
  19573. constructor( ...members ) {
  19574. super();
  19575. /**
  19576. * An array of nodes which defines the output.
  19577. *
  19578. * @type {Array<Node>}
  19579. */
  19580. this.members = members;
  19581. /**
  19582. * This flag can be used for type testing.
  19583. *
  19584. * @type {Boolean}
  19585. * @readonly
  19586. * @default true
  19587. */
  19588. this.isOutputStructNode = true;
  19589. }
  19590. getNodeType( builder ) {
  19591. const properties = builder.getNodeProperties( this );
  19592. if ( properties.membersLayout === undefined ) {
  19593. const members = this.members;
  19594. const membersLayout = [];
  19595. for ( let i = 0; i < members.length; i ++ ) {
  19596. const name = 'm' + i;
  19597. const type = members[ i ].getNodeType( builder );
  19598. membersLayout.push( { name, type, index: i } );
  19599. }
  19600. properties.membersLayout = membersLayout;
  19601. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  19602. }
  19603. return properties.structType.name;
  19604. }
  19605. generate( builder ) {
  19606. const propertyName = builder.getOutputStructName();
  19607. const members = this.members;
  19608. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19609. for ( let i = 0; i < members.length; i ++ ) {
  19610. const snippet = members[ i ].build( builder );
  19611. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19612. }
  19613. return propertyName;
  19614. }
  19615. }
  19616. /**
  19617. * TSL function for creating an output struct node.
  19618. *
  19619. * @function
  19620. * @param {...Node} members - A parameter list of nodes.
  19621. * @returns {OutputStructNode}
  19622. */
  19623. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19624. /** @module MRTNode **/
  19625. /**
  19626. * Returns the MRT texture index for the given name.
  19627. *
  19628. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19629. * @param {String} name - The name of the MRT texture which index is requested.
  19630. * @return {Number} The texture index.
  19631. */
  19632. function getTextureIndex( textures, name ) {
  19633. for ( let i = 0; i < textures.length; i ++ ) {
  19634. if ( textures[ i ].name === name ) {
  19635. return i;
  19636. }
  19637. }
  19638. return - 1;
  19639. }
  19640. /**
  19641. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19642. * post-processing is shown below:
  19643. * ```js
  19644. * const mrtNode = mrt( {
  19645. * output: output,
  19646. * normal: normalView
  19647. * } ) );
  19648. * ```
  19649. * The MRT output is defined as a dictionary.
  19650. *
  19651. * @augments OutputStructNode
  19652. */
  19653. class MRTNode extends OutputStructNode {
  19654. static get type() {
  19655. return 'MRTNode';
  19656. }
  19657. /**
  19658. * Constructs a new output struct node.
  19659. *
  19660. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19661. */
  19662. constructor( outputNodes ) {
  19663. super();
  19664. /**
  19665. * A dictionary representing the MRT outputs. The key
  19666. * is the name of the output, the value the node which produces
  19667. * the output result.
  19668. *
  19669. * @type {Object<String, Node>}
  19670. */
  19671. this.outputNodes = outputNodes;
  19672. /**
  19673. * This flag can be used for type testing.
  19674. *
  19675. * @type {Boolean}
  19676. * @readonly
  19677. * @default true
  19678. */
  19679. this.isMRTNode = true;
  19680. }
  19681. /**
  19682. * Returns `true` if the MRT node has an output with the given name.
  19683. *
  19684. * @param {String} name - The name of the output.
  19685. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19686. */
  19687. has( name ) {
  19688. return this.outputNodes[ name ] !== undefined;
  19689. }
  19690. /**
  19691. * Returns the output node for the given name.
  19692. *
  19693. * @param {String} name - The name of the output.
  19694. * @return {Node} The output node.
  19695. */
  19696. get( name ) {
  19697. return this.outputNodes[ name ];
  19698. }
  19699. /**
  19700. * Merges the outputs of the given MRT node with the outputs of this node.
  19701. *
  19702. * @param {MRTNode} mrtNode - The MRT to merge.
  19703. * @return {MRTNode} A new MRT node with merged outputs..
  19704. */
  19705. merge( mrtNode ) {
  19706. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19707. return mrt( outputs );
  19708. }
  19709. setup( builder ) {
  19710. const outputNodes = this.outputNodes;
  19711. const mrt = builder.renderer.getRenderTarget();
  19712. const members = [];
  19713. const textures = mrt.textures;
  19714. for ( const name in outputNodes ) {
  19715. const index = getTextureIndex( textures, name );
  19716. members[ index ] = vec4( outputNodes[ name ] );
  19717. }
  19718. this.members = members;
  19719. return super.setup( builder );
  19720. }
  19721. }
  19722. /**
  19723. * TSL function for creating a MRT node.
  19724. *
  19725. * @function
  19726. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19727. * @returns {MRTNode}
  19728. */
  19729. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19730. /** @module Hash **/
  19731. /**
  19732. * Generates a hash value in the range `[0, 1]` from the given seed.
  19733. *
  19734. * @method
  19735. * @param {Node<float>} seed - The seed.
  19736. * @return {Node<float>} The hash value.
  19737. */
  19738. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19739. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19740. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19741. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19742. const result = word.shiftRight( 22 ).bitXor( word );
  19743. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19744. } );
  19745. /** @module MathUtils **/
  19746. /**
  19747. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19748. * The corners are mapped to `0` and the center to `1`.
  19749. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19750. *
  19751. * @method
  19752. * @param {Node<float>} x - The value to remap.
  19753. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19754. * @return {Node<float>} The remapped value.
  19755. */
  19756. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19757. /**
  19758. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19759. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  19760. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19761. *
  19762. * @method
  19763. * @param {Node<float>} x - The value to remap.
  19764. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19765. * @return {Node<float>} The remapped value.
  19766. */
  19767. 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 ) );
  19768. /**
  19769. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19770. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19771. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19772. *
  19773. * @method
  19774. * @param {Node<float>} x - The value to remap.
  19775. * @param {Node<float>} a - First control parameter.
  19776. * @param {Node<float>} b - Second control parameter.
  19777. * @return {Node<float>} The remapped value.
  19778. */
  19779. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19780. /**
  19781. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19782. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19783. *
  19784. * @method
  19785. * @param {Node<float>} x - The value to compute the sin for.
  19786. * @param {Node<float>} k - Controls the amount of bounces.
  19787. * @return {Node<float>} The result value.
  19788. */
  19789. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19790. // https://github.com/cabbibo/glsl-tri-noise-3d
  19791. /** @module TriNoise3D **/
  19792. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19793. return x.fract().sub( .5 ).abs();
  19794. } ).setLayout( {
  19795. name: 'tri',
  19796. type: 'float',
  19797. inputs: [
  19798. { name: 'x', type: 'float' }
  19799. ]
  19800. } );
  19801. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19802. 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. ) ) ) ) );
  19803. } ).setLayout( {
  19804. name: 'tri3',
  19805. type: 'vec3',
  19806. inputs: [
  19807. { name: 'p', type: 'vec3' }
  19808. ]
  19809. } );
  19810. /**
  19811. * Generates a noise value from the given position, speed and time parameters.
  19812. *
  19813. * @method
  19814. * @param {Node<vec3>} position - The position.
  19815. * @param {Node<float>} speed - The speed.
  19816. * @param {Node<float>} time - The time.
  19817. * @return {Node<float>} The generated noise.
  19818. */
  19819. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19820. const p = vec3( position ).toVar();
  19821. const z = float( 1.4 ).toVar();
  19822. const rz = float( 0.0 ).toVar();
  19823. const bp = vec3( p ).toVar();
  19824. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19825. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19826. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19827. bp.mulAssign( 1.8 );
  19828. z.mulAssign( 1.5 );
  19829. p.mulAssign( 1.2 );
  19830. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19831. rz.addAssign( t.div( z ) );
  19832. bp.addAssign( 0.14 );
  19833. } );
  19834. return rz;
  19835. } ).setLayout( {
  19836. name: 'triNoise3D',
  19837. type: 'float',
  19838. inputs: [
  19839. { name: 'position', type: 'vec3' },
  19840. { name: 'speed', type: 'float' },
  19841. { name: 'time', type: 'float' }
  19842. ]
  19843. } );
  19844. /** @module FunctionOverloadingNode **/
  19845. /**
  19846. * This class allows to define multiple overloaded versions
  19847. * of the same function. Depending on the parameters of the function
  19848. * call, the node picks the best-fit overloaded version.
  19849. *
  19850. * @augments Node
  19851. */
  19852. class FunctionOverloadingNode extends Node {
  19853. static get type() {
  19854. return 'FunctionOverloadingNode';
  19855. }
  19856. /**
  19857. * Constructs a new function overloading node.
  19858. *
  19859. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19860. * @param {...Node} parametersNodes - A list of parameter nodes.
  19861. */
  19862. constructor( functionNodes = [], ...parametersNodes ) {
  19863. super();
  19864. /**
  19865. * Array of `Fn` function definitions.
  19866. *
  19867. * @type {Array<Function>}
  19868. */
  19869. this.functionNodes = functionNodes;
  19870. /**
  19871. * A list of parameter nodes.
  19872. *
  19873. * @type {Array<Node>}
  19874. */
  19875. this.parametersNodes = parametersNodes;
  19876. /**
  19877. * The selected overloaded function call.
  19878. *
  19879. * @private
  19880. * @type {ShaderCallNodeInternal}
  19881. */
  19882. this._candidateFnCall = null;
  19883. /**
  19884. * This node is marked as global.
  19885. *
  19886. * @type {Boolean}
  19887. * @default true
  19888. */
  19889. this.global = true;
  19890. }
  19891. /**
  19892. * This method is overwritten since the node type is inferred from
  19893. * the function's return type.
  19894. *
  19895. * @param {NodeBuilder} builder - The current node builder.
  19896. * @return {String} The node type.
  19897. */
  19898. getNodeType() {
  19899. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19900. }
  19901. setup( builder ) {
  19902. const params = this.parametersNodes;
  19903. let candidateFnCall = this._candidateFnCall;
  19904. if ( candidateFnCall === null ) {
  19905. let candidateFn = null;
  19906. let candidateScore = - 1;
  19907. for ( const functionNode of this.functionNodes ) {
  19908. const shaderNode = functionNode.shaderNode;
  19909. const layout = shaderNode.layout;
  19910. if ( layout === null ) {
  19911. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19912. }
  19913. const inputs = layout.inputs;
  19914. if ( params.length === inputs.length ) {
  19915. let score = 0;
  19916. for ( let i = 0; i < params.length; i ++ ) {
  19917. const param = params[ i ];
  19918. const input = inputs[ i ];
  19919. if ( param.getNodeType( builder ) === input.type ) {
  19920. score ++;
  19921. } else {
  19922. score = 0;
  19923. }
  19924. }
  19925. if ( score > candidateScore ) {
  19926. candidateFn = functionNode;
  19927. candidateScore = score;
  19928. }
  19929. }
  19930. }
  19931. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19932. }
  19933. return candidateFnCall;
  19934. }
  19935. }
  19936. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19937. /**
  19938. * TSL function for creating a function overloading node.
  19939. *
  19940. * @function
  19941. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19942. * @returns {FunctionOverloadingNode}
  19943. */
  19944. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19945. /** @module Timer **/
  19946. /**
  19947. * Represents the elapsed time in seconds.
  19948. *
  19949. * @type {UniformNode<float>}
  19950. */
  19951. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19952. /**
  19953. * Represents the delta time in seconds.
  19954. *
  19955. * @type {UniformNode<float>}
  19956. */
  19957. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19958. /**
  19959. * Represents the current frame ID.
  19960. *
  19961. * @type {UniformNode<uint>}
  19962. */
  19963. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19964. // Deprecated
  19965. /**
  19966. * @function
  19967. * @deprecated since r170. Use {@link time} instead.
  19968. *
  19969. * @param {Number} [timeScale=1] - The time scale.
  19970. * @returns {UniformNode<float>}
  19971. */
  19972. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19973. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19974. return time.mul( timeScale );
  19975. };
  19976. /**
  19977. * @function
  19978. * @deprecated since r170. Use {@link time} instead.
  19979. *
  19980. * @param {Number} [timeScale=1] - The time scale.
  19981. * @returns {UniformNode<float>}
  19982. */
  19983. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19984. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19985. return time.mul( timeScale );
  19986. };
  19987. /**
  19988. * @function
  19989. * @deprecated since r170. Use {@link deltaTime} instead.
  19990. *
  19991. * @param {Number} [timeScale=1] - The time scale.
  19992. * @returns {UniformNode<float>}
  19993. */
  19994. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19995. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19996. return deltaTime.mul( timeScale );
  19997. };
  19998. /** @module Oscillators **/
  19999. /**
  20000. * Generates a sine wave oscillation based on a timer.
  20001. *
  20002. * @method
  20003. * @param {Node<float>} t - The timer to generate the oscillation with.
  20004. * @return {Node<float>} The oscillation node.
  20005. */
  20006. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  20007. /**
  20008. * Generates a square wave oscillation based on a timer.
  20009. *
  20010. * @method
  20011. * @param {Node<float>} t - The timer to generate the oscillation with.
  20012. * @return {Node<float>} The oscillation node.
  20013. */
  20014. const oscSquare = ( t = time ) => t.fract().round();
  20015. /**
  20016. * Generates a triangle wave oscillation based on a timer.
  20017. *
  20018. * @method
  20019. * @param {Node<float>} t - The timer to generate the oscillation with.
  20020. * @return {Node<float>} The oscillation node.
  20021. */
  20022. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  20023. /**
  20024. * Generates a sawtooth wave oscillation based on a timer.
  20025. *
  20026. * @method
  20027. * @param {Node<float>} t - The timer to generate the oscillation with.
  20028. * @return {Node<float>} The oscillation node.
  20029. */
  20030. const oscSawtooth = ( t = time ) => t.fract();
  20031. /** @module UVUtils **/
  20032. /**
  20033. * Rotates the given uv coordinates around a center point
  20034. *
  20035. * @method
  20036. * @param {Node<vec2>} uv - The uv coordinates.
  20037. * @param {Node<float>} rotation - The rotation defined in radians.
  20038. * @param {Node<vec2>} center - The center of rotation
  20039. * @return {Node<vec2>} The rotated uv coordinates.
  20040. */
  20041. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  20042. return rotate( uv.sub( center ), rotation ).add( center );
  20043. } );
  20044. /**
  20045. * Applies a spherical warping effect to the given uv coordinates.
  20046. *
  20047. * @method
  20048. * @param {Node<vec2>} uv - The uv coordinates.
  20049. * @param {Node<float>} strength - The strength of the effect.
  20050. * @param {Node<vec2>} center - The center point
  20051. * @return {Node<vec2>} The updated uv coordinates.
  20052. */
  20053. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  20054. const delta = uv.sub( center );
  20055. const delta2 = delta.dot( delta );
  20056. const delta4 = delta2.mul( delta2 );
  20057. const deltaOffset = delta4.mul( strength );
  20058. return uv.add( delta.mul( deltaOffset ) );
  20059. } );
  20060. /** @module SpriteUtils **/
  20061. /**
  20062. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  20063. * oriented always towards the camera.
  20064. *
  20065. * ```js
  20066. * material.vertexNode = billboarding();
  20067. * ```
  20068. *
  20069. * @method
  20070. * @param {Object} config - The configuration object.
  20071. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  20072. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  20073. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  20074. * @return {Node<vec3>} The updated vertex position in clip space.
  20075. */
  20076. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  20077. let worldMatrix;
  20078. if ( position !== null ) {
  20079. worldMatrix = modelWorldMatrix.toVar();
  20080. worldMatrix[ 3 ][ 0 ] = position.x;
  20081. worldMatrix[ 3 ][ 1 ] = position.y;
  20082. worldMatrix[ 3 ][ 2 ] = position.z;
  20083. } else {
  20084. worldMatrix = modelWorldMatrix;
  20085. }
  20086. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  20087. if ( defined( horizontal ) ) {
  20088. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  20089. modelViewMatrix[ 0 ][ 1 ] = 0;
  20090. modelViewMatrix[ 0 ][ 2 ] = 0;
  20091. }
  20092. if ( defined( vertical ) ) {
  20093. modelViewMatrix[ 1 ][ 0 ] = 0;
  20094. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  20095. modelViewMatrix[ 1 ][ 2 ] = 0;
  20096. }
  20097. modelViewMatrix[ 2 ][ 0 ] = 0;
  20098. modelViewMatrix[ 2 ][ 1 ] = 0;
  20099. modelViewMatrix[ 2 ][ 2 ] = 1;
  20100. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  20101. } );
  20102. /** @module ViewportUtils **/
  20103. /**
  20104. * A special version of a screen uv function that involves a depth comparison
  20105. * when computing the final uvs. The function mitigates visual errors when
  20106. * using viewport texture nodes for refraction purposes. Without this function
  20107. * objects in front of a refractive surface might appear on the refractive surface
  20108. * which is incorrect.
  20109. *
  20110. * @method
  20111. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  20112. * @return {Node<vec2>} The update uv coordinates.
  20113. */
  20114. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  20115. const depth = linearDepth();
  20116. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  20117. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  20118. return finalUV;
  20119. } );
  20120. /** @module SpriteSheetUVNode **/
  20121. /**
  20122. * Can be used to compute texture coordinates for animated sprite sheets.
  20123. *
  20124. * ```js
  20125. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  20126. *
  20127. * material.colorNode = texture( spriteSheet, uvNode );
  20128. * ```
  20129. *
  20130. * @augments Node
  20131. */
  20132. class SpriteSheetUVNode extends Node {
  20133. static get type() {
  20134. return 'SpriteSheetUVNode';
  20135. }
  20136. /**
  20137. * Constructs a new sprite sheet uv node.
  20138. *
  20139. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  20140. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  20141. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  20142. */
  20143. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  20144. super( 'vec2' );
  20145. /**
  20146. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  20147. *
  20148. * @type {Node<vec2>}
  20149. */
  20150. this.countNode = countNode;
  20151. /**
  20152. * The uv node.
  20153. *
  20154. * @type {Node<vec2>}
  20155. */
  20156. this.uvNode = uvNode;
  20157. /**
  20158. * The node that defines the current frame/sprite.
  20159. *
  20160. * @type {Node<float>}
  20161. */
  20162. this.frameNode = frameNode;
  20163. }
  20164. setup() {
  20165. const { frameNode, uvNode, countNode } = this;
  20166. const { width, height } = countNode;
  20167. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  20168. const column = frameNum.mod( width );
  20169. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  20170. const scale = countNode.reciprocal();
  20171. const uvFrameOffset = vec2( column, row );
  20172. return uvNode.add( uvFrameOffset ).mul( scale );
  20173. }
  20174. }
  20175. /**
  20176. * TSL function for creating a sprite sheet uv node.
  20177. *
  20178. * @function
  20179. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  20180. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  20181. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  20182. * @returns {SpriteSheetUVNode}
  20183. */
  20184. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  20185. /** @module TriplanarTexturesNode **/
  20186. /**
  20187. * Can be used for triplanar texture mapping.
  20188. *
  20189. * ```js
  20190. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  20191. * ```
  20192. *
  20193. * @augments Node
  20194. */
  20195. class TriplanarTexturesNode extends Node {
  20196. static get type() {
  20197. return 'TriplanarTexturesNode';
  20198. }
  20199. /**
  20200. * Constructs a new triplanar textures node.
  20201. *
  20202. * @param {Node} textureXNode - First texture node.
  20203. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20204. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20205. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  20206. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  20207. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  20208. */
  20209. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  20210. super( 'vec4' );
  20211. /**
  20212. * First texture node.
  20213. *
  20214. * @type {Node}
  20215. */
  20216. this.textureXNode = textureXNode;
  20217. /**
  20218. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20219. *
  20220. * @type {Node}
  20221. * @default null
  20222. */
  20223. this.textureYNode = textureYNode;
  20224. /**
  20225. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20226. *
  20227. * @type {Node}
  20228. * @default null
  20229. */
  20230. this.textureZNode = textureZNode;
  20231. /**
  20232. * The scale node.
  20233. *
  20234. * @type {Node<float>}
  20235. * @default float(1)
  20236. */
  20237. this.scaleNode = scaleNode;
  20238. /**
  20239. * Vertex positions in local space.
  20240. *
  20241. * @type {Node<vec3>}
  20242. * @default positionLocal
  20243. */
  20244. this.positionNode = positionNode;
  20245. /**
  20246. * Normals in local space.
  20247. *
  20248. * @type {Node<vec3>}
  20249. * @default normalLocal
  20250. */
  20251. this.normalNode = normalNode;
  20252. }
  20253. setup() {
  20254. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  20255. // Ref: https://github.com/keijiro/StandardTriplanar
  20256. // Blending factor of triplanar mapping
  20257. let bf = normalNode.abs().normalize();
  20258. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  20259. // Triplanar mapping
  20260. const tx = positionNode.yz.mul( scaleNode );
  20261. const ty = positionNode.zx.mul( scaleNode );
  20262. const tz = positionNode.xy.mul( scaleNode );
  20263. // Base color
  20264. const textureX = textureXNode.value;
  20265. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  20266. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  20267. const cx = texture( textureX, tx ).mul( bf.x );
  20268. const cy = texture( textureY, ty ).mul( bf.y );
  20269. const cz = texture( textureZ, tz ).mul( bf.z );
  20270. return add( cx, cy, cz );
  20271. }
  20272. }
  20273. /**
  20274. * TSL function for creating a triplanar textures node.
  20275. *
  20276. * @function
  20277. * @param {Node} textureXNode - First texture node.
  20278. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20279. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20280. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  20281. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  20282. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  20283. * @returns {TriplanarTexturesNode}
  20284. */
  20285. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  20286. /**
  20287. * TSL function for creating a triplanar textures node.
  20288. *
  20289. * @function
  20290. * @param {Node} textureXNode - First texture node.
  20291. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  20292. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  20293. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  20294. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  20295. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  20296. * @returns {TriplanarTexturesNode}
  20297. */
  20298. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  20299. /** @module ReflectorNode **/
  20300. const _reflectorPlane = new Plane();
  20301. const _normal = new Vector3();
  20302. const _reflectorWorldPosition = new Vector3();
  20303. const _cameraWorldPosition = new Vector3();
  20304. const _rotationMatrix = new Matrix4();
  20305. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  20306. const clipPlane = new Vector4();
  20307. const _view = new Vector3();
  20308. const _target = new Vector3();
  20309. const _q = new Vector4();
  20310. const _size$2 = new Vector2();
  20311. const _defaultRT = new RenderTarget();
  20312. const _defaultUV = screenUV.flipX();
  20313. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  20314. let _inReflector = false;
  20315. /**
  20316. * This node can be used to implement mirror-like flat reflective surfaces.
  20317. *
  20318. * ```js
  20319. * const groundReflector = reflector();
  20320. * material.colorNode = groundReflector;
  20321. *
  20322. * const plane = new Mesh( geometry, material );
  20323. * plane.add( groundReflector.target );
  20324. * ```
  20325. *
  20326. * @augments module:TextureNode~TextureNode
  20327. */
  20328. class ReflectorNode extends TextureNode {
  20329. static get type() {
  20330. return 'ReflectorNode';
  20331. }
  20332. /**
  20333. * Constructs a new reflector node.
  20334. *
  20335. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20336. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20337. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20338. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20339. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20340. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20341. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20342. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20343. */
  20344. constructor( parameters = {} ) {
  20345. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  20346. /**
  20347. * A reference to the internal reflector base node which holds the actual implementation.
  20348. *
  20349. * @private
  20350. * @type {ReflectorBaseNode?}
  20351. * @default null
  20352. */
  20353. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  20354. /**
  20355. * A reference to the internal depth node.
  20356. *
  20357. * @private
  20358. * @type {Node?}
  20359. * @default null
  20360. */
  20361. this._depthNode = null;
  20362. this.setUpdateMatrix( false );
  20363. }
  20364. /**
  20365. * A reference to the internal reflector node.
  20366. *
  20367. * @type {ReflectorBaseNode}
  20368. */
  20369. get reflector() {
  20370. return this._reflectorBaseNode;
  20371. }
  20372. /**
  20373. * A reference to 3D object the reflector is linked to.
  20374. *
  20375. * @type {Object3D}
  20376. */
  20377. get target() {
  20378. return this._reflectorBaseNode.target;
  20379. }
  20380. /**
  20381. * Returns a node representing the mirror's depth. That can be used
  20382. * to implement more advanced reflection effects like distance attenuation.
  20383. *
  20384. * @return {Node} The depth node.
  20385. */
  20386. getDepthNode() {
  20387. if ( this._depthNode === null ) {
  20388. if ( this._reflectorBaseNode.depth !== true ) {
  20389. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  20390. }
  20391. this._depthNode = nodeObject( new ReflectorNode( {
  20392. defaultTexture: _defaultRT.depthTexture,
  20393. reflector: this._reflectorBaseNode
  20394. } ) );
  20395. }
  20396. return this._depthNode;
  20397. }
  20398. setup( builder ) {
  20399. // ignore if used in post-processing
  20400. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  20401. return super.setup( builder );
  20402. }
  20403. clone() {
  20404. const texture = new this.constructor( this.reflectorNode );
  20405. texture._reflectorBaseNode = this._reflectorBaseNode;
  20406. return texture;
  20407. }
  20408. }
  20409. /**
  20410. * Holds the actual implementation of the reflector.
  20411. *
  20412. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  20413. * in `ReflectorNode`, see #29619.
  20414. *
  20415. * @private
  20416. * @augments Node
  20417. */
  20418. class ReflectorBaseNode extends Node {
  20419. static get type() {
  20420. return 'ReflectorBaseNode';
  20421. }
  20422. /**
  20423. * Constructs a new reflector base node.
  20424. *
  20425. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  20426. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20427. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20428. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20429. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20430. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20431. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20432. */
  20433. constructor( textureNode, parameters = {} ) {
  20434. super();
  20435. const {
  20436. target = new Object3D(),
  20437. resolution = 1,
  20438. generateMipmaps = false,
  20439. bounces = true,
  20440. depth = false
  20441. } = parameters;
  20442. /**
  20443. * Represents the rendered reflections as a texture node.
  20444. *
  20445. * @type {TextureNode}
  20446. */
  20447. this.textureNode = textureNode;
  20448. /**
  20449. * The 3D object the reflector is linked to.
  20450. *
  20451. * @type {Object3D}
  20452. * @default {new Object3D()}
  20453. */
  20454. this.target = target;
  20455. /**
  20456. * The resolution scale.
  20457. *
  20458. * @type {Number}
  20459. * @default {1}
  20460. */
  20461. this.resolution = resolution;
  20462. /**
  20463. * Whether mipmaps should be generated or not.
  20464. *
  20465. * @type {Boolean}
  20466. * @default {false}
  20467. */
  20468. this.generateMipmaps = generateMipmaps;
  20469. /**
  20470. * Whether reflectors can render other reflector nodes or not.
  20471. *
  20472. * @type {Boolean}
  20473. * @default {true}
  20474. */
  20475. this.bounces = bounces;
  20476. /**
  20477. * Whether depth data should be generated or not.
  20478. *
  20479. * @type {Boolean}
  20480. * @default {false}
  20481. */
  20482. this.depth = depth;
  20483. /**
  20484. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  20485. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  20486. *
  20487. * @type {String}
  20488. * @default 'render'
  20489. */
  20490. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  20491. /**
  20492. * Weak map for managing virtual cameras.
  20493. *
  20494. * @type {WeakMap<Camera, Camera>}
  20495. */
  20496. this.virtualCameras = new WeakMap();
  20497. /**
  20498. * Weak map for managing render targets.
  20499. *
  20500. * @type {WeakMap<Camera, RenderTarget>}
  20501. */
  20502. this.renderTargets = new WeakMap();
  20503. }
  20504. /**
  20505. * Updates the resolution of the internal render target.
  20506. *
  20507. * @private
  20508. * @param {RenderTarget} renderTarget - The render target to resize.
  20509. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  20510. */
  20511. _updateResolution( renderTarget, renderer ) {
  20512. const resolution = this.resolution;
  20513. renderer.getDrawingBufferSize( _size$2 );
  20514. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  20515. }
  20516. setup( builder ) {
  20517. this._updateResolution( _defaultRT, builder.renderer );
  20518. return super.setup( builder );
  20519. }
  20520. /**
  20521. * Returns a virtual camera for the given camera. The virtual camera is used to
  20522. * render the scene from the reflector's view so correct reflections can be produced.
  20523. *
  20524. * @param {Camera} camera - The scene's camera.
  20525. * @return {Camera} The corresponding virtual camera.
  20526. */
  20527. getVirtualCamera( camera ) {
  20528. let virtualCamera = this.virtualCameras.get( camera );
  20529. if ( virtualCamera === undefined ) {
  20530. virtualCamera = camera.clone();
  20531. this.virtualCameras.set( camera, virtualCamera );
  20532. }
  20533. return virtualCamera;
  20534. }
  20535. /**
  20536. * Returns a render target for the given camera. The reflections are rendered
  20537. * into this render target.
  20538. *
  20539. * @param {Camera} camera - The scene's camera.
  20540. * @return {RenderTarget} The render target.
  20541. */
  20542. getRenderTarget( camera ) {
  20543. let renderTarget = this.renderTargets.get( camera );
  20544. if ( renderTarget === undefined ) {
  20545. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20546. if ( this.generateMipmaps === true ) {
  20547. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20548. renderTarget.texture.generateMipmaps = true;
  20549. }
  20550. if ( this.depth === true ) {
  20551. renderTarget.depthTexture = new DepthTexture();
  20552. }
  20553. this.renderTargets.set( camera, renderTarget );
  20554. }
  20555. return renderTarget;
  20556. }
  20557. updateBefore( frame ) {
  20558. if ( this.bounces === false && _inReflector ) return false;
  20559. _inReflector = true;
  20560. const { scene, camera, renderer, material } = frame;
  20561. const { target } = this;
  20562. const virtualCamera = this.getVirtualCamera( camera );
  20563. const renderTarget = this.getRenderTarget( virtualCamera );
  20564. renderer.getDrawingBufferSize( _size$2 );
  20565. this._updateResolution( renderTarget, renderer );
  20566. //
  20567. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20568. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20569. _rotationMatrix.extractRotation( target.matrixWorld );
  20570. _normal.set( 0, 0, 1 );
  20571. _normal.applyMatrix4( _rotationMatrix );
  20572. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20573. // Avoid rendering when reflector is facing away
  20574. if ( _view.dot( _normal ) > 0 ) return;
  20575. _view.reflect( _normal ).negate();
  20576. _view.add( _reflectorWorldPosition );
  20577. _rotationMatrix.extractRotation( camera.matrixWorld );
  20578. _lookAtPosition.set( 0, 0, - 1 );
  20579. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20580. _lookAtPosition.add( _cameraWorldPosition );
  20581. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20582. _target.reflect( _normal ).negate();
  20583. _target.add( _reflectorWorldPosition );
  20584. //
  20585. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20586. virtualCamera.position.copy( _view );
  20587. virtualCamera.up.set( 0, 1, 0 );
  20588. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20589. virtualCamera.up.reflect( _normal );
  20590. virtualCamera.lookAt( _target );
  20591. virtualCamera.near = camera.near;
  20592. virtualCamera.far = camera.far;
  20593. virtualCamera.updateMatrixWorld();
  20594. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20595. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20596. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20597. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20598. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20599. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20600. const projectionMatrix = virtualCamera.projectionMatrix;
  20601. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20602. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20603. _q.z = - 1.0;
  20604. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20605. // Calculate the scaled plane vector
  20606. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20607. const clipBias = 0;
  20608. // Replacing the third row of the projection matrix
  20609. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20610. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20611. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20612. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20613. //
  20614. this.textureNode.value = renderTarget.texture;
  20615. if ( this.depth === true ) {
  20616. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20617. }
  20618. material.visible = false;
  20619. const currentRenderTarget = renderer.getRenderTarget();
  20620. const currentMRT = renderer.getMRT();
  20621. const currentAutoClear = renderer.autoClear;
  20622. renderer.setMRT( null );
  20623. renderer.setRenderTarget( renderTarget );
  20624. renderer.autoClear = true;
  20625. renderer.render( scene, virtualCamera );
  20626. renderer.setMRT( currentMRT );
  20627. renderer.setRenderTarget( currentRenderTarget );
  20628. renderer.autoClear = currentAutoClear;
  20629. material.visible = true;
  20630. _inReflector = false;
  20631. }
  20632. }
  20633. /**
  20634. * TSL function for creating a reflector node.
  20635. *
  20636. * @function
  20637. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20638. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20639. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20640. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20641. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20642. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20643. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20644. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20645. * @returns {ReflectorNode}
  20646. */
  20647. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20648. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  20649. /**
  20650. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20651. *
  20652. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20653. *
  20654. * @private
  20655. * @augments BufferGeometry
  20656. */
  20657. class QuadGeometry extends BufferGeometry {
  20658. /**
  20659. * Constructs a new quad geometry.
  20660. *
  20661. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20662. */
  20663. constructor( flipY = false ) {
  20664. super();
  20665. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20666. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  20667. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20668. }
  20669. }
  20670. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20671. /**
  20672. * This module is a helper for passes which need to render a full
  20673. * screen effect which is quite common in context of post processing.
  20674. *
  20675. * The intended usage is to reuse a single quad mesh for rendering
  20676. * subsequent passes by just reassigning the `material` reference.
  20677. *
  20678. * @augments Mesh
  20679. */
  20680. class QuadMesh extends Mesh {
  20681. /**
  20682. * Constructs a new quad mesh.
  20683. *
  20684. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20685. */
  20686. constructor( material = null ) {
  20687. super( _geometry, material );
  20688. /**
  20689. * The camera to render the quad mesh with.
  20690. *
  20691. * @type {OrthographicCamera}
  20692. * @readonly
  20693. */
  20694. this.camera = _camera;
  20695. /**
  20696. * This flag can be used for type testing.
  20697. *
  20698. * @type {Boolean}
  20699. * @readonly
  20700. * @default true
  20701. */
  20702. this.isQuadMesh = true;
  20703. }
  20704. /**
  20705. * Async version of `render()`.
  20706. *
  20707. * @async
  20708. * @param {Renderer} renderer - The renderer.
  20709. * @return {Promise} A Promise that resolves when the render has been finished.
  20710. */
  20711. async renderAsync( renderer ) {
  20712. return renderer.renderAsync( this, _camera );
  20713. }
  20714. /**
  20715. * Renders the quad mesh
  20716. *
  20717. * @param {Renderer} renderer - The renderer.
  20718. */
  20719. render( renderer ) {
  20720. renderer.render( this, _camera );
  20721. }
  20722. }
  20723. /** @module RTTNode **/
  20724. const _size$1 = /*@__PURE__*/ new Vector2();
  20725. /**
  20726. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20727. * This module is especially relevant in context of post processing where certain nodes require
  20728. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20729. * on this module, the node system can automatically ensure texture input if required.
  20730. *
  20731. * @augments module:TextureNode~TextureNode
  20732. */
  20733. class RTTNode extends TextureNode {
  20734. static get type() {
  20735. return 'RTTNode';
  20736. }
  20737. /**
  20738. * Constructs a new RTT node.
  20739. *
  20740. * @param {Node} node - The node to render a texture with.
  20741. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20742. * @param {Number?} [height=null] - The height of the internal render target.
  20743. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20744. */
  20745. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20746. const renderTarget = new RenderTarget( width, height, options );
  20747. super( renderTarget.texture, uv() );
  20748. /**
  20749. * The node to render a texture with.
  20750. *
  20751. * @type {Node}
  20752. */
  20753. this.node = node;
  20754. /**
  20755. * The width of the internal render target.
  20756. * If not width is applied, the render target is automatically resized.
  20757. *
  20758. * @type {Number?}
  20759. * @default null
  20760. */
  20761. this.width = width;
  20762. /**
  20763. * The height of the internal render target.
  20764. *
  20765. * @type {Number?}
  20766. * @default null
  20767. */
  20768. this.height = height;
  20769. /**
  20770. * The pixel ratio
  20771. *
  20772. * @type {Number}
  20773. * @default 1
  20774. */
  20775. this.pixelRatio = 1;
  20776. /**
  20777. * The render target
  20778. *
  20779. * @type {RenderTarget}
  20780. */
  20781. this.renderTarget = renderTarget;
  20782. /**
  20783. * Whether the texture requires an update or not.
  20784. *
  20785. * @type {Boolean}
  20786. * @default true
  20787. */
  20788. this.textureNeedsUpdate = true;
  20789. /**
  20790. * Whether the texture should automatically be updated or not.
  20791. *
  20792. * @type {Boolean}
  20793. * @default true
  20794. */
  20795. this.autoUpdate = true;
  20796. /**
  20797. * The node which is used with the quad mesh for RTT.
  20798. *
  20799. * @private
  20800. * @type {Node}
  20801. * @default null
  20802. */
  20803. this._rttNode = null;
  20804. /**
  20805. * The internal quad mesh for RTT.
  20806. *
  20807. * @private
  20808. * @type {QuadMesh}
  20809. */
  20810. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20811. /**
  20812. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20813. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20814. *
  20815. * @type {String}
  20816. * @default 'render'
  20817. */
  20818. this.updateBeforeType = NodeUpdateType.RENDER;
  20819. }
  20820. /**
  20821. * Whether the internal render target should automatically be resized or not.
  20822. *
  20823. * @type {Boolean}
  20824. * @readonly
  20825. * @default true
  20826. */
  20827. get autoSize() {
  20828. return this.width === null;
  20829. }
  20830. setup( builder ) {
  20831. this._rttNode = this.node.context( builder.getSharedContext() );
  20832. this._quadMesh.material.name = 'RTT';
  20833. this._quadMesh.material.needsUpdate = true;
  20834. return super.setup( builder );
  20835. }
  20836. /**
  20837. * Sets the size of the internal render target
  20838. *
  20839. * @param {Number} width - The width to set.
  20840. * @param {Number} height - The width to set.
  20841. */
  20842. setSize( width, height ) {
  20843. this.width = width;
  20844. this.height = height;
  20845. const effectiveWidth = width * this.pixelRatio;
  20846. const effectiveHeight = height * this.pixelRatio;
  20847. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20848. this.textureNeedsUpdate = true;
  20849. }
  20850. /**
  20851. * Sets the pixel ratio. This will also resize the render target.
  20852. *
  20853. * @param {Number} pixelRatio - The pixel ratio to set.
  20854. */
  20855. setPixelRatio( pixelRatio ) {
  20856. this.pixelRatio = pixelRatio;
  20857. this.setSize( this.width, this.height );
  20858. }
  20859. updateBefore( { renderer } ) {
  20860. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20861. this.textureNeedsUpdate = false;
  20862. //
  20863. if ( this.autoSize === true ) {
  20864. this.pixelRatio = renderer.getPixelRatio();
  20865. const size = renderer.getSize( _size$1 );
  20866. this.setSize( size.width, size.height );
  20867. }
  20868. //
  20869. this._quadMesh.material.fragmentNode = this._rttNode;
  20870. //
  20871. const currentRenderTarget = renderer.getRenderTarget();
  20872. renderer.setRenderTarget( this.renderTarget );
  20873. this._quadMesh.render( renderer );
  20874. renderer.setRenderTarget( currentRenderTarget );
  20875. }
  20876. clone() {
  20877. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20878. newNode.sampler = this.sampler;
  20879. newNode.referenceNode = this;
  20880. return newNode;
  20881. }
  20882. }
  20883. /**
  20884. * TSL function for creating a RTT node.
  20885. *
  20886. * @function
  20887. * @param {Node} node - The node to render a texture with.
  20888. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20889. * @param {Number?} [height=null] - The height of the internal render target.
  20890. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20891. * @returns {RTTNode}
  20892. */
  20893. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20894. /**
  20895. * TSL function for converting nodes to textures nodes.
  20896. *
  20897. * @function
  20898. * @param {Node} node - The node to render a texture with.
  20899. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20900. * @param {Number?} [height=null] - The height of the internal render target.
  20901. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20902. * @returns {RTTNode}
  20903. */
  20904. const convertToTexture = ( node, ...params ) => {
  20905. if ( node.isTextureNode ) return node;
  20906. if ( node.isPassNode ) return node.getTextureNode();
  20907. return rtt( node, ...params );
  20908. };
  20909. /** @module PostProcessingUtils **/
  20910. /**
  20911. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20912. * depth value and the camera's inverse projection matrix.
  20913. *
  20914. * @method
  20915. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20916. * @param {Node<float>} depth - The fragment's depth value.
  20917. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20918. * @return {Node<vec3>} The fragments position in view space.
  20919. */
  20920. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20921. let clipSpacePosition;
  20922. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20923. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20924. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20925. } else {
  20926. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20927. }
  20928. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20929. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20930. } );
  20931. /**
  20932. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20933. * and the camera's projection matrix
  20934. *
  20935. * @method
  20936. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20937. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20938. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20939. */
  20940. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20941. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20942. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20943. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20944. } );
  20945. /**
  20946. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20947. * target is available or if flat surface normals are required.
  20948. *
  20949. * @method
  20950. * @param {Node<vec2>} uv - The texture coordinate.
  20951. * @param {DepthTexture} depthTexture - The depth texture.
  20952. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20953. * @return {Node<vec3>} The computed normal vector.
  20954. */
  20955. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20956. const size = textureSize( textureLoad( depthTexture ) );
  20957. const p = ivec2( uv.mul( size ) ).toVar();
  20958. const c0 = textureLoad( depthTexture, p ).toVar();
  20959. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20960. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20961. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20962. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20963. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20964. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20965. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20966. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20967. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20968. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20969. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20970. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20971. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20972. 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 ) ) );
  20973. 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 ) ) );
  20974. return normalize( cross( dpdx, dpdy ) );
  20975. } );
  20976. /**
  20977. * This special type of instanced buffer attribute is intended for compute shaders.
  20978. * In earlier three.js versions it was only possible to update attribute data
  20979. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20980. * new material system and renderer it is now possible to use compute shaders
  20981. * to compute the data for an attribute more efficiently on the GPU.
  20982. *
  20983. * The idea is to create an instance of this class and provide it as an input
  20984. * to {@link module:StorageBufferNode}.
  20985. *
  20986. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20987. *
  20988. * @augments InstancedBufferAttribute
  20989. */
  20990. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20991. /**
  20992. * Constructs a new storage instanced buffer attribute.
  20993. *
  20994. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20995. * The subsequent parameters are then obsolete.
  20996. * @param {Number} itemSize - The item size.
  20997. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20998. */
  20999. constructor( count, itemSize, typeClass = Float32Array ) {
  21000. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  21001. super( array, itemSize );
  21002. /**
  21003. * This flag can be used for type testing.
  21004. *
  21005. * @type {Boolean}
  21006. * @readonly
  21007. * @default true
  21008. */
  21009. this.isStorageInstancedBufferAttribute = true;
  21010. }
  21011. }
  21012. /**
  21013. * This special type of buffer attribute is intended for compute shaders.
  21014. * In earlier three.js versions it was only possible to update attribute data
  21015. * on the CPU via JavaScript and then upload the data to the GPU. With the
  21016. * new material system and renderer it is now possible to use compute shaders
  21017. * to compute the data for an attribute more efficiently on the GPU.
  21018. *
  21019. * The idea is to create an instance of this class and provide it as an input
  21020. * to {@link module:StorageBufferNode}.
  21021. *
  21022. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  21023. *
  21024. * @augments BufferAttribute
  21025. */
  21026. class StorageBufferAttribute extends BufferAttribute {
  21027. /**
  21028. * Constructs a new storage buffer attribute.
  21029. *
  21030. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  21031. * The subsequent parameters are then obsolete.
  21032. * @param {Number} itemSize - The item size.
  21033. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  21034. */
  21035. constructor( count, itemSize, typeClass = Float32Array ) {
  21036. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  21037. super( array, itemSize );
  21038. /**
  21039. * This flag can be used for type testing.
  21040. *
  21041. * @type {Boolean}
  21042. * @readonly
  21043. * @default true
  21044. */
  21045. this.isStorageBufferAttribute = true;
  21046. }
  21047. }
  21048. /** @module StorageArrayElementNode **/
  21049. /**
  21050. * This class enables element access on instances of {@link StorageBufferNode}.
  21051. * In most cases, it is indirectly used when accessing elements with the
  21052. * {@link StorageBufferNode#element} method.
  21053. *
  21054. * ```js
  21055. * const position = positionStorage.element( instanceIndex );
  21056. * ```
  21057. *
  21058. * @augments ArrayElementNode
  21059. */
  21060. class StorageArrayElementNode extends ArrayElementNode {
  21061. static get type() {
  21062. return 'StorageArrayElementNode';
  21063. }
  21064. /**
  21065. * Constructs storage buffer element node.
  21066. *
  21067. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  21068. * @param {Node} indexNode - The index node that defines the element access.
  21069. */
  21070. constructor( storageBufferNode, indexNode ) {
  21071. super( storageBufferNode, indexNode );
  21072. /**
  21073. * This flag can be used for type testing.
  21074. *
  21075. * @type {Boolean}
  21076. * @readonly
  21077. * @default true
  21078. */
  21079. this.isStorageArrayElementNode = true;
  21080. }
  21081. /**
  21082. * The storage buffer node.
  21083. *
  21084. * @param {Node} value
  21085. * @type {StorageBufferNode}
  21086. */
  21087. set storageBufferNode( value ) {
  21088. this.node = value;
  21089. }
  21090. get storageBufferNode() {
  21091. return this.node;
  21092. }
  21093. getMemberType( builder, name ) {
  21094. const structTypeNode = this.storageBufferNode.structTypeNode;
  21095. if ( structTypeNode ) {
  21096. return structTypeNode.getMemberType( builder, name );
  21097. }
  21098. return 'void';
  21099. }
  21100. setup( builder ) {
  21101. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  21102. if ( this.node.isPBO === true ) {
  21103. builder.setupPBO( this.node );
  21104. }
  21105. }
  21106. return super.setup( builder );
  21107. }
  21108. generate( builder, output ) {
  21109. let snippet;
  21110. const isAssignContext = builder.context.assign;
  21111. //
  21112. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  21113. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  21114. snippet = builder.generatePBO( this );
  21115. } else {
  21116. snippet = this.node.build( builder );
  21117. }
  21118. } else {
  21119. snippet = super.generate( builder );
  21120. }
  21121. if ( isAssignContext !== true ) {
  21122. const type = this.getNodeType( builder );
  21123. snippet = builder.format( snippet, type, output );
  21124. }
  21125. return snippet;
  21126. }
  21127. }
  21128. /**
  21129. * TSL function for creating a storage element node.
  21130. *
  21131. * @function
  21132. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  21133. * @param {Node} indexNode - The index node that defines the element access.
  21134. * @returns {StorageArrayElementNode}
  21135. */
  21136. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  21137. /** @module StorageBufferNode **/
  21138. /**
  21139. * This node is used in context of compute shaders and allows to define a
  21140. * storage buffer for data. A typical workflow is to create instances of
  21141. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  21142. * setup up a compute shader that writes into the buffers and then convert
  21143. * the storage buffers to attribute nodes for rendering.
  21144. *
  21145. * ```js
  21146. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  21147. *
  21148. * const computeInit = Fn( () => { // the compute shader
  21149. *
  21150. * const position = positionBuffer.element( instanceIndex );
  21151. *
  21152. * // compute position data
  21153. *
  21154. * position.x = 1;
  21155. * position.y = 1;
  21156. * position.z = 1;
  21157. *
  21158. * } )().compute( particleCount );
  21159. *
  21160. * const particleMaterial = new THREE.SpriteNodeMaterial();
  21161. * particleMaterial.positionNode = positionBuffer.toAttribute();
  21162. *
  21163. * renderer.computeAsync( computeInit );
  21164. *
  21165. * ```
  21166. *
  21167. * @augments BufferNode
  21168. */
  21169. class StorageBufferNode extends BufferNode {
  21170. static get type() {
  21171. return 'StorageBufferNode';
  21172. }
  21173. /**
  21174. * Constructs a new storage buffer node.
  21175. *
  21176. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21177. * @param {(String|Struct)?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  21178. * @param {Number} [bufferCount=0] - The buffer count.
  21179. */
  21180. constructor( value, bufferType = null, bufferCount = 0 ) {
  21181. let nodeType, structTypeNode = null;
  21182. if ( bufferType && bufferType.isStruct ) {
  21183. nodeType = 'struct';
  21184. structTypeNode = bufferType.layout;
  21185. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  21186. nodeType = getTypeFromLength( value.itemSize );
  21187. bufferCount = value.count;
  21188. } else {
  21189. nodeType = bufferType;
  21190. }
  21191. super( value, nodeType, bufferCount );
  21192. /**
  21193. * This flag can be used for type testing.
  21194. *
  21195. * @type {Boolean}
  21196. * @readonly
  21197. * @default true
  21198. */
  21199. this.isStorageBufferNode = true;
  21200. /**
  21201. * The buffer struct type.
  21202. *
  21203. * @type {structTypeNode?}
  21204. * @default null
  21205. */
  21206. this.structTypeNode = structTypeNode;
  21207. /**
  21208. * The access type of the texture node.
  21209. *
  21210. * @type {String}
  21211. * @default 'readWrite'
  21212. */
  21213. this.access = NodeAccess.READ_WRITE;
  21214. /**
  21215. * Whether the node is atomic or not.
  21216. *
  21217. * @type {Boolean}
  21218. * @default false
  21219. */
  21220. this.isAtomic = false;
  21221. /**
  21222. * Whether the node represents a PBO or not.
  21223. * Only relevant for WebGL.
  21224. *
  21225. * @type {Boolean}
  21226. * @default false
  21227. */
  21228. this.isPBO = false;
  21229. /**
  21230. * A reference to the internal buffer attribute node.
  21231. *
  21232. * @type {BufferAttributeNode?}
  21233. * @default null
  21234. */
  21235. this._attribute = null;
  21236. /**
  21237. * A reference to the internal varying node.
  21238. *
  21239. * @type {VaryingNode?}
  21240. * @default null
  21241. */
  21242. this._varying = null;
  21243. /**
  21244. * `StorageBufferNode` sets this property to `true` by default.
  21245. *
  21246. * @type {Boolean}
  21247. * @default true
  21248. */
  21249. this.global = true;
  21250. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  21251. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  21252. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  21253. else value.isStorageBufferAttribute = true;
  21254. }
  21255. }
  21256. /**
  21257. * This method is overwritten since the buffer data might be shared
  21258. * and thus the hash should be shared as well.
  21259. *
  21260. * @param {NodeBuilder} builder - The current node builder.
  21261. * @return {String} The hash.
  21262. */
  21263. getHash( builder ) {
  21264. if ( this.bufferCount === 0 ) {
  21265. let bufferData = builder.globalCache.getData( this.value );
  21266. if ( bufferData === undefined ) {
  21267. bufferData = {
  21268. node: this
  21269. };
  21270. builder.globalCache.setData( this.value, bufferData );
  21271. }
  21272. return bufferData.node.uuid;
  21273. }
  21274. return this.uuid;
  21275. }
  21276. /**
  21277. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  21278. *
  21279. * @param {NodeBuilder} builder - The current node builder.
  21280. * @return {String} The input type.
  21281. */
  21282. getInputType( /*builder*/ ) {
  21283. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  21284. }
  21285. /**
  21286. * Enables element access with the given index node.
  21287. *
  21288. * @param {IndexNode} indexNode - The index node.
  21289. * @return {StorageArrayElementNode} A node representing the element access.
  21290. */
  21291. element( indexNode ) {
  21292. return storageElement( this, indexNode );
  21293. }
  21294. /**
  21295. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  21296. *
  21297. * @param {Boolean} value - The value so set.
  21298. * @return {StorageBufferNode} A reference to this node.
  21299. */
  21300. setPBO( value ) {
  21301. this.isPBO = value;
  21302. return this;
  21303. }
  21304. /**
  21305. * Returns the `isPBO` value.
  21306. *
  21307. * @return {Boolean} Whether the node represents a PBO or not.
  21308. */
  21309. getPBO() {
  21310. return this.isPBO;
  21311. }
  21312. /**
  21313. * Defines the node access.
  21314. *
  21315. * @param {String} value - The node access.
  21316. * @return {StorageBufferNode} A reference to this node.
  21317. */
  21318. setAccess( value ) {
  21319. this.access = value;
  21320. return this;
  21321. }
  21322. /**
  21323. * Convenience method for configuring a read-only node access.
  21324. *
  21325. * @return {StorageBufferNode} A reference to this node.
  21326. */
  21327. toReadOnly() {
  21328. return this.setAccess( NodeAccess.READ_ONLY );
  21329. }
  21330. /**
  21331. * Defines whether the node is atomic or not.
  21332. *
  21333. * @param {Boolean} value - The atomic flag.
  21334. * @return {StorageBufferNode} A reference to this node.
  21335. */
  21336. setAtomic( value ) {
  21337. this.isAtomic = value;
  21338. return this;
  21339. }
  21340. /**
  21341. * Convenience method for making this node atomic.
  21342. *
  21343. * @return {StorageBufferNode} A reference to this node.
  21344. */
  21345. toAtomic() {
  21346. return this.setAtomic( true );
  21347. }
  21348. /**
  21349. * Returns attribute data for this storage buffer node.
  21350. *
  21351. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  21352. */
  21353. getAttributeData() {
  21354. if ( this._attribute === null ) {
  21355. this._attribute = bufferAttribute( this.value );
  21356. this._varying = varying( this._attribute );
  21357. }
  21358. return {
  21359. attribute: this._attribute,
  21360. varying: this._varying
  21361. };
  21362. }
  21363. /**
  21364. * This method is overwritten since the node type from the availability of storage buffers
  21365. * and the attribute data.
  21366. *
  21367. * @param {NodeBuilder} builder - The current node builder.
  21368. * @return {String} The node type.
  21369. */
  21370. getNodeType( builder ) {
  21371. if ( this.structTypeNode !== null ) {
  21372. return this.structTypeNode.getNodeType( builder );
  21373. }
  21374. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21375. return super.getNodeType( builder );
  21376. }
  21377. const { attribute } = this.getAttributeData();
  21378. return attribute.getNodeType( builder );
  21379. }
  21380. /**
  21381. * Generates the code snippet of the storage buffer node.
  21382. *
  21383. * @param {NodeBuilder} builder - The current node builder.
  21384. * @return {String} The generated code snippet.
  21385. */
  21386. generate( builder ) {
  21387. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  21388. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21389. return super.generate( builder );
  21390. }
  21391. const { attribute, varying } = this.getAttributeData();
  21392. const output = varying.build( builder );
  21393. builder.registerTransform( output, attribute );
  21394. return output;
  21395. }
  21396. }
  21397. /**
  21398. * TSL function for creating a storage buffer node.
  21399. *
  21400. * @function
  21401. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21402. * @param {(String|Struct)?} [type=null] - The buffer type (e.g. `'vec3'`).
  21403. * @param {Number} [count=0] - The buffer count.
  21404. * @returns {StorageBufferNode}
  21405. */
  21406. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  21407. /**
  21408. * @function
  21409. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  21410. *
  21411. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21412. * @param {String?} type - The buffer type (e.g. `'vec3'`).
  21413. * @param {Number} count - The buffer count.
  21414. * @returns {StorageBufferNode}
  21415. */
  21416. const storageObject = ( value, type, count ) => { // @deprecated, r171
  21417. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  21418. return storage( value, type, count ).setPBO( true );
  21419. };
  21420. /** @module Arrays **/
  21421. /**
  21422. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  21423. *
  21424. * @function
  21425. * @param {Number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21426. * @param {String|Struct} [type='float'] - The data type.
  21427. * @returns {StorageBufferNode}
  21428. */
  21429. const attributeArray = ( count, type = 'float' ) => {
  21430. let itemSize, typedArray;
  21431. if ( type.isStruct === true ) {
  21432. itemSize = type.layout.getLength();
  21433. typedArray = getTypedArrayFromType( 'float' );
  21434. } else {
  21435. itemSize = getLengthFromType( type );
  21436. typedArray = getTypedArrayFromType( type );
  21437. }
  21438. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  21439. const node = storage( buffer, type, count );
  21440. return node;
  21441. };
  21442. /**
  21443. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  21444. *
  21445. * @function
  21446. * @param {Number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  21447. * @param {String|Struct} [type='float'] - The data type.
  21448. * @returns {StorageBufferNode}
  21449. */
  21450. const instancedArray = ( count, type = 'float' ) => {
  21451. let itemSize, typedArray;
  21452. if ( type.isStruct === true ) {
  21453. itemSize = type.layout.getLength();
  21454. typedArray = getTypedArrayFromType( 'float' );
  21455. } else {
  21456. itemSize = getLengthFromType( type );
  21457. typedArray = getTypedArrayFromType( type );
  21458. }
  21459. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  21460. const node = storage( buffer, type, count );
  21461. return node;
  21462. };
  21463. /** @module VertexColorNode **/
  21464. /**
  21465. * An attribute node for representing vertex colors.
  21466. *
  21467. * @augments module:AttributeNode~AttributeNode
  21468. */
  21469. class VertexColorNode extends AttributeNode {
  21470. static get type() {
  21471. return 'VertexColorNode';
  21472. }
  21473. /**
  21474. * Constructs a new vertex color node.
  21475. *
  21476. * @param {Number} [index=0] - The attribute index.
  21477. */
  21478. constructor( index = 0 ) {
  21479. super( null, 'vec4' );
  21480. /**
  21481. * This flag can be used for type testing.
  21482. *
  21483. * @type {Boolean}
  21484. * @readonly
  21485. * @default true
  21486. */
  21487. this.isVertexColorNode = true;
  21488. /**
  21489. * The attribute index to enable more than one sets of vertex colors.
  21490. *
  21491. * @type {Number}
  21492. * @default 0
  21493. */
  21494. this.index = index;
  21495. }
  21496. /**
  21497. * Overwrites the default implementation by honoring the attribute index.
  21498. *
  21499. * @param {NodeBuilder} builder - The current node builder.
  21500. * @return {String} The attribute name.
  21501. */
  21502. getAttributeName( /*builder*/ ) {
  21503. const index = this.index;
  21504. return 'color' + ( index > 0 ? index : '' );
  21505. }
  21506. generate( builder ) {
  21507. const attributeName = this.getAttributeName( builder );
  21508. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  21509. let result;
  21510. if ( geometryAttribute === true ) {
  21511. result = super.generate( builder );
  21512. } else {
  21513. // Vertex color fallback should be white
  21514. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  21515. }
  21516. return result;
  21517. }
  21518. serialize( data ) {
  21519. super.serialize( data );
  21520. data.index = this.index;
  21521. }
  21522. deserialize( data ) {
  21523. super.deserialize( data );
  21524. this.index = data.index;
  21525. }
  21526. }
  21527. /**
  21528. * TSL function for creating a reference node.
  21529. *
  21530. * @function
  21531. * @param {Number} index - The attribute index.
  21532. * @returns {VertexColorNode}
  21533. */
  21534. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  21535. /** @module PointUVNode **/
  21536. /**
  21537. * A node for representing the uv coordinates of points.
  21538. *
  21539. * Can only be used with a WebGL backend. In WebGPU, point
  21540. * primitives always have the size of one pixel and can thus
  21541. * can't be used as sprite-like objects that display textures.
  21542. *
  21543. * @augments Node
  21544. */
  21545. class PointUVNode extends Node {
  21546. static get type() {
  21547. return 'PointUVNode';
  21548. }
  21549. /**
  21550. * Constructs a new point uv node.
  21551. */
  21552. constructor() {
  21553. super( 'vec2' );
  21554. /**
  21555. * This flag can be used for type testing.
  21556. *
  21557. * @type {Boolean}
  21558. * @readonly
  21559. * @default true
  21560. */
  21561. this.isPointUVNode = true;
  21562. }
  21563. generate( /*builder*/ ) {
  21564. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  21565. }
  21566. }
  21567. /**
  21568. * TSL object that represents the uv coordinates of points.
  21569. *
  21570. * @type {PointUVNode}
  21571. */
  21572. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  21573. const _e1 = /*@__PURE__*/ new Euler();
  21574. const _m1 = /*@__PURE__*/ new Matrix4();
  21575. /** @module SceneNode **/
  21576. /**
  21577. * This module allows access to a collection of scene properties. The following predefined TSL objects
  21578. * are available for easier use:
  21579. *
  21580. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  21581. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21582. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21583. *
  21584. * @augments Node
  21585. */
  21586. class SceneNode extends Node {
  21587. static get type() {
  21588. return 'SceneNode';
  21589. }
  21590. /**
  21591. * Constructs a new scene node.
  21592. *
  21593. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21594. * @param {Scene?} [scene=null] - A reference to the scene.
  21595. */
  21596. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21597. super();
  21598. /**
  21599. * The scope defines the type of scene property that is accessed.
  21600. *
  21601. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21602. */
  21603. this.scope = scope;
  21604. /**
  21605. * A reference to the scene that is going to be accessed.
  21606. *
  21607. * @type {Scene?}
  21608. * @default null
  21609. */
  21610. this.scene = scene;
  21611. }
  21612. /**
  21613. * Depending on the scope, the method returns a different type of node that represents
  21614. * the respective scene property.
  21615. *
  21616. * @param {NodeBuilder} builder - The current node builder.
  21617. * @return {Node} The output node.
  21618. */
  21619. setup( builder ) {
  21620. const scope = this.scope;
  21621. const scene = this.scene !== null ? this.scene : builder.scene;
  21622. let output;
  21623. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21624. output = reference( 'backgroundBlurriness', 'float', scene );
  21625. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21626. output = reference( 'backgroundIntensity', 'float', scene );
  21627. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21628. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21629. const background = scene.background;
  21630. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21631. _e1.copy( scene.backgroundRotation );
  21632. // accommodate left-handed frame
  21633. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  21634. _m1.makeRotationFromEuler( _e1 );
  21635. } else {
  21636. _m1.identity();
  21637. }
  21638. return _m1;
  21639. } );
  21640. } else {
  21641. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21642. }
  21643. return output;
  21644. }
  21645. }
  21646. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21647. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21648. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21649. /**
  21650. * TSL object that represents the scene's background blurriness.
  21651. *
  21652. * @type {SceneNode}
  21653. */
  21654. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21655. /**
  21656. * TSL object that represents the scene's background intensity.
  21657. *
  21658. * @type {SceneNode}
  21659. */
  21660. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21661. /**
  21662. * TSL object that represents the scene's background rotation.
  21663. *
  21664. * @type {SceneNode}
  21665. */
  21666. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21667. /** @module StorageTextureNode **/
  21668. /**
  21669. * This special version of a texture node can be used to
  21670. * write data into a storage texture with a compute shader.
  21671. *
  21672. * ```js
  21673. * const storageTexture = new THREE.StorageTexture( width, height );
  21674. *
  21675. * const computeTexture = Fn( ( { storageTexture } ) => {
  21676. *
  21677. * const posX = instanceIndex.modInt( width );
  21678. * const posY = instanceIndex.div( width );
  21679. * const indexUV = uvec2( posX, posY );
  21680. *
  21681. * // generate RGB values
  21682. *
  21683. * const r = 1;
  21684. * const g = 1;
  21685. * const b = 1;
  21686. *
  21687. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21688. *
  21689. * } );
  21690. *
  21691. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21692. * renderer.computeAsync( computeNode );
  21693. * ```
  21694. *
  21695. * This node can only be used with a WebGPU backend.
  21696. *
  21697. * @augments module:TextureNode~TextureNode
  21698. */
  21699. class StorageTextureNode extends TextureNode {
  21700. static get type() {
  21701. return 'StorageTextureNode';
  21702. }
  21703. /**
  21704. * Constructs a new storage texture node.
  21705. *
  21706. * @param {StorageTexture} value - The storage texture.
  21707. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21708. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21709. */
  21710. constructor( value, uvNode, storeNode = null ) {
  21711. super( value, uvNode );
  21712. /**
  21713. * The value node that should be stored in the texture.
  21714. *
  21715. * @type {Node?}
  21716. * @default null
  21717. */
  21718. this.storeNode = storeNode;
  21719. /**
  21720. * This flag can be used for type testing.
  21721. *
  21722. * @type {Boolean}
  21723. * @readonly
  21724. * @default true
  21725. */
  21726. this.isStorageTextureNode = true;
  21727. /**
  21728. * The access type of the texture node.
  21729. *
  21730. * @type {String}
  21731. * @default 'writeOnly'
  21732. */
  21733. this.access = NodeAccess.WRITE_ONLY;
  21734. }
  21735. /**
  21736. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21737. *
  21738. * @param {NodeBuilder} builder - The current node builder.
  21739. * @return {String} The input type.
  21740. */
  21741. getInputType( /*builder*/ ) {
  21742. return 'storageTexture';
  21743. }
  21744. setup( builder ) {
  21745. super.setup( builder );
  21746. const properties = builder.getNodeProperties( this );
  21747. properties.storeNode = this.storeNode;
  21748. }
  21749. /**
  21750. * Defines the node access.
  21751. *
  21752. * @param {String} value - The node access.
  21753. * @return {StorageTextureNode} A reference to this node.
  21754. */
  21755. setAccess( value ) {
  21756. this.access = value;
  21757. return this;
  21758. }
  21759. /**
  21760. * Generates the code snippet of the stroge node. If no `storeNode`
  21761. * is defined, the texture node is generated as normal texture.
  21762. *
  21763. * @param {NodeBuilder} builder - The current node builder.
  21764. * @param {String} output - The current output.
  21765. * @return {String} The generated code snippet.
  21766. */
  21767. generate( builder, output ) {
  21768. let snippet;
  21769. if ( this.storeNode !== null ) {
  21770. snippet = this.generateStore( builder );
  21771. } else {
  21772. snippet = super.generate( builder, output );
  21773. }
  21774. return snippet;
  21775. }
  21776. /**
  21777. * Convenience method for configuring a read/write node access.
  21778. *
  21779. * @return {StorageTextureNode} A reference to this node.
  21780. */
  21781. toReadWrite() {
  21782. return this.setAccess( NodeAccess.READ_WRITE );
  21783. }
  21784. /**
  21785. * Convenience method for configuring a read-only node access.
  21786. *
  21787. * @return {StorageTextureNode} A reference to this node.
  21788. */
  21789. toReadOnly() {
  21790. return this.setAccess( NodeAccess.READ_ONLY );
  21791. }
  21792. /**
  21793. * Convenience method for configuring a write-only node access.
  21794. *
  21795. * @return {StorageTextureNode} A reference to this node.
  21796. */
  21797. toWriteOnly() {
  21798. return this.setAccess( NodeAccess.WRITE_ONLY );
  21799. }
  21800. /**
  21801. * Generates the code snippet of the storage texture node.
  21802. *
  21803. * @param {NodeBuilder} builder - The current node builder.
  21804. */
  21805. generateStore( builder ) {
  21806. const properties = builder.getNodeProperties( this );
  21807. const { uvNode, storeNode } = properties;
  21808. const textureProperty = super.generate( builder, 'property' );
  21809. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21810. const storeSnippet = storeNode.build( builder, 'vec4' );
  21811. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21812. builder.addLineFlowCode( snippet, this );
  21813. }
  21814. }
  21815. /**
  21816. * TSL function for creating a storage texture node.
  21817. *
  21818. * @function
  21819. * @param {StorageTexture} value - The storage texture.
  21820. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21821. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21822. * @returns {StorageTextureNode}
  21823. */
  21824. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21825. /**
  21826. * TODO: Explain difference to `storageTexture()`.
  21827. *
  21828. * @function
  21829. * @param {StorageTexture} value - The storage texture.
  21830. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21831. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21832. * @returns {StorageTextureNode}
  21833. */
  21834. const textureStore = ( value, uvNode, storeNode ) => {
  21835. const node = storageTexture( value, uvNode, storeNode );
  21836. if ( storeNode !== null ) node.append();
  21837. return node;
  21838. };
  21839. /** @module UserDataNode **/
  21840. /**
  21841. * A special type of reference node that allows to link values in
  21842. * `userData` fields to node objects.
  21843. * ```js
  21844. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21845. *
  21846. * const material = new THREE.SpriteNodeMaterial();
  21847. * material.rotationNode = userData( 'rotation', 'float' );
  21848. * ```
  21849. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21850. * will automatically be updated when the `rotation` user data field changes.
  21851. *
  21852. * @augments module:ReferenceNode~ReferenceNode
  21853. */
  21854. class UserDataNode extends ReferenceNode {
  21855. static get type() {
  21856. return 'UserDataNode';
  21857. }
  21858. /**
  21859. * Constructs a new user data node.
  21860. *
  21861. * @param {String} property - The property name that should be referenced by the node.
  21862. * @param {String} inputType - The node data type of the reference.
  21863. * @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.
  21864. */
  21865. constructor( property, inputType, userData = null ) {
  21866. super( property, inputType, userData );
  21867. /**
  21868. * A reference to the `userData` object. If not provided, the `userData`
  21869. * property of the 3D object that uses the node material is evaluated.
  21870. *
  21871. * @type {Object?}
  21872. * @default null
  21873. */
  21874. this.userData = userData;
  21875. }
  21876. /**
  21877. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21878. * `userData` field.
  21879. *
  21880. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21881. * @return {Object} A reference to the `userData` field.
  21882. */
  21883. updateReference( state ) {
  21884. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21885. return this.reference;
  21886. }
  21887. }
  21888. /**
  21889. * TSL function for creating a user data node.
  21890. *
  21891. * @function
  21892. * @param {String} name - The property name that should be referenced by the node.
  21893. * @param {String} inputType - The node data type of the reference.
  21894. * @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.
  21895. * @returns {UserDataNode}
  21896. */
  21897. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21898. const _objectData = new WeakMap();
  21899. /** @module VelocityNode **/
  21900. /**
  21901. * A node for representing motion or velocity vectors. Foundation
  21902. * for advanced post processing effects like motion blur or TRAA.
  21903. *
  21904. * The node keeps track of the model, view and projection matrices
  21905. * of the previous frame and uses them to compute offsets in NDC space.
  21906. * These offsets represent the final velocity.
  21907. *
  21908. * @augments TempNode
  21909. */
  21910. class VelocityNode extends TempNode {
  21911. static get type() {
  21912. return 'VelocityNode';
  21913. }
  21914. /**
  21915. * Constructs a new vertex color node.
  21916. */
  21917. constructor() {
  21918. super( 'vec2' );
  21919. /**
  21920. * The current projection matrix.
  21921. *
  21922. * @type {Matrix4?}
  21923. * @default null
  21924. */
  21925. this.projectionMatrix = null;
  21926. /**
  21927. * Overwritten since velocity nodes are updated per object.
  21928. *
  21929. * @type {String}
  21930. * @default 'object'
  21931. */
  21932. this.updateType = NodeUpdateType.OBJECT;
  21933. /**
  21934. * Overwritten since velocity nodes save data after the update.
  21935. *
  21936. * @type {String}
  21937. * @default 'object'
  21938. */
  21939. this.updateAfterType = NodeUpdateType.OBJECT;
  21940. /**
  21941. * Uniform node representing the previous model matrix in world space.
  21942. *
  21943. * @type {UniformNode<mat4>}
  21944. * @default null
  21945. */
  21946. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21947. /**
  21948. * Uniform node representing the previous projection matrix.
  21949. *
  21950. * @type {UniformNode<mat4>}
  21951. * @default null
  21952. */
  21953. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21954. /**
  21955. * Uniform node representing the previous view matrix.
  21956. *
  21957. * @type {UniformNode<mat4>}
  21958. * @default null
  21959. */
  21960. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21961. }
  21962. /**
  21963. * Sets the given projection matrix.
  21964. *
  21965. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21966. */
  21967. setProjectionMatrix( projectionMatrix ) {
  21968. this.projectionMatrix = projectionMatrix;
  21969. }
  21970. /**
  21971. * Updates velocity specific uniforms.
  21972. *
  21973. * @param {NodeFrame} frame - A reference to the current node frame.
  21974. */
  21975. update( { frameId, camera, object } ) {
  21976. const previousModelMatrix = getPreviousMatrix( object );
  21977. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21978. //
  21979. const cameraData = getData( camera );
  21980. if ( cameraData.frameId !== frameId ) {
  21981. cameraData.frameId = frameId;
  21982. if ( cameraData.previousProjectionMatrix === undefined ) {
  21983. cameraData.previousProjectionMatrix = new Matrix4();
  21984. cameraData.previousCameraViewMatrix = new Matrix4();
  21985. cameraData.currentProjectionMatrix = new Matrix4();
  21986. cameraData.currentCameraViewMatrix = new Matrix4();
  21987. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21988. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21989. } else {
  21990. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21991. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21992. }
  21993. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21994. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21995. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21996. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21997. }
  21998. }
  21999. /**
  22000. * Overwritten to updated velocity specific uniforms.
  22001. *
  22002. * @param {NodeFrame} frame - A reference to the current node frame.
  22003. */
  22004. updateAfter( { object } ) {
  22005. getPreviousMatrix( object ).copy( object.matrixWorld );
  22006. }
  22007. /**
  22008. * Implements the velocity computation based on the previous and current vertex data.
  22009. *
  22010. * @param {NodeBuilder} builder - A reference to the current node builder.
  22011. * @return {Node<vec2>} The motion vector.
  22012. */
  22013. setup( /*builder*/ ) {
  22014. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  22015. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  22016. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22017. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  22018. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  22019. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  22020. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  22021. return velocity;
  22022. }
  22023. }
  22024. function getData( object ) {
  22025. let objectData = _objectData.get( object );
  22026. if ( objectData === undefined ) {
  22027. objectData = {};
  22028. _objectData.set( object, objectData );
  22029. }
  22030. return objectData;
  22031. }
  22032. function getPreviousMatrix( object, index = 0 ) {
  22033. const objectData = getData( object );
  22034. let matrix = objectData[ index ];
  22035. if ( matrix === undefined ) {
  22036. objectData[ index ] = matrix = new Matrix4();
  22037. }
  22038. return matrix;
  22039. }
  22040. /**
  22041. * TSL object that represents the velocity of a render pass.
  22042. *
  22043. * @type {VelocityNode}
  22044. */
  22045. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  22046. /** @module BlendModes **/
  22047. /**
  22048. * Represents a "Color Burn" blend mode.
  22049. *
  22050. * It's designed to darken the base layer's colors based on the color of the blend layer.
  22051. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  22052. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  22053. *
  22054. * @method
  22055. * @param {Node<vec3>} base - The base color.
  22056. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  22057. * @return {Node<vec3>} The result.
  22058. */
  22059. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22060. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  22061. } ).setLayout( {
  22062. name: 'blendBurn',
  22063. type: 'vec3',
  22064. inputs: [
  22065. { name: 'base', type: 'vec3' },
  22066. { name: 'blend', type: 'vec3' }
  22067. ]
  22068. } );
  22069. /**
  22070. * Represents a "Color Dodge" blend mode.
  22071. *
  22072. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  22073. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  22074. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  22075. *
  22076. * @method
  22077. * @param {Node<vec3>} base - The base color.
  22078. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  22079. * @return {Node<vec3>} The result.
  22080. */
  22081. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22082. return min$1( base.div( blend.oneMinus() ), 1.0 );
  22083. } ).setLayout( {
  22084. name: 'blendDodge',
  22085. type: 'vec3',
  22086. inputs: [
  22087. { name: 'base', type: 'vec3' },
  22088. { name: 'blend', type: 'vec3' }
  22089. ]
  22090. } );
  22091. /**
  22092. * Represents a "Screen" blend mode.
  22093. *
  22094. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  22095. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  22096. * effects.
  22097. *
  22098. * @method
  22099. * @param {Node<vec3>} base - The base color.
  22100. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  22101. * @return {Node<vec3>} The result.
  22102. */
  22103. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22104. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  22105. } ).setLayout( {
  22106. name: 'blendScreen',
  22107. type: 'vec3',
  22108. inputs: [
  22109. { name: 'base', type: 'vec3' },
  22110. { name: 'blend', type: 'vec3' }
  22111. ]
  22112. } );
  22113. /**
  22114. * Represents a "Overlay" blend mode.
  22115. *
  22116. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  22117. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  22118. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  22119. *
  22120. * @method
  22121. * @param {Node<vec3>} base - The base color.
  22122. * @param {Node<vec3>} blend - The blend color
  22123. * @return {Node<vec3>} The result.
  22124. */
  22125. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22126. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  22127. } ).setLayout( {
  22128. name: 'blendOverlay',
  22129. type: 'vec3',
  22130. inputs: [
  22131. { name: 'base', type: 'vec3' },
  22132. { name: 'blend', type: 'vec3' }
  22133. ]
  22134. } );
  22135. /**
  22136. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  22137. * It assumes both input colors have non-preumiltiplied alpha.
  22138. *
  22139. * @method
  22140. * @param {Node<vec4>} base - The base color.
  22141. * @param {Node<vec4>} blend - The blend color
  22142. * @return {Node<vec4>} The result.
  22143. */
  22144. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  22145. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  22146. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  22147. } ).setLayout( {
  22148. name: 'blendColor',
  22149. type: 'vec4',
  22150. inputs: [
  22151. { name: 'base', type: 'vec4' },
  22152. { name: 'blend', type: 'vec4' }
  22153. ]
  22154. } );
  22155. // Deprecated
  22156. /**
  22157. * @function
  22158. * @deprecated since r171. Use {@link blendBurn} instead.
  22159. *
  22160. * @param {...any} params
  22161. * @returns {Function}
  22162. */
  22163. const burn = ( ...params ) => { // @deprecated, r171
  22164. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  22165. return blendBurn( params );
  22166. };
  22167. /**
  22168. * @function
  22169. * @deprecated since r171. Use {@link blendDodge} instead.
  22170. *
  22171. * @param {...any} params
  22172. * @returns {Function}
  22173. */
  22174. const dodge = ( ...params ) => { // @deprecated, r171
  22175. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  22176. return blendDodge( params );
  22177. };
  22178. /**
  22179. * @method
  22180. * @deprecated since r171. Use {@link blendScreen} instead.
  22181. *
  22182. * @param {...any} params
  22183. * @returns {Function}
  22184. */
  22185. const screen = ( ...params ) => { // @deprecated, r171
  22186. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  22187. return blendScreen( params );
  22188. };
  22189. /**
  22190. * @method
  22191. * @deprecated since r171. Use {@link blendOverlay} instead.
  22192. *
  22193. * @param {...any} params
  22194. * @returns {Function}
  22195. */
  22196. const overlay = ( ...params ) => { // @deprecated, r171
  22197. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  22198. return blendOverlay( params );
  22199. };
  22200. /** @module ColorAdjustment **/
  22201. /**
  22202. * Computes a grayscale value for the given RGB color value.
  22203. *
  22204. * @method
  22205. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  22206. * @return {Node<vec3>} The grayscale color.
  22207. */
  22208. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22209. return luminance( color.rgb );
  22210. } );
  22211. /**
  22212. * Super-saturates or desaturates the given RGB color.
  22213. *
  22214. * @method
  22215. * @param {Node<vec3>} color - The input color.
  22216. * @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.
  22217. * @return {Node<vec3>} The saturated color.
  22218. */
  22219. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  22220. return adjustment.mix( luminance( color.rgb ), color.rgb );
  22221. } );
  22222. /**
  22223. * Selectively enhance the intensity of less saturated RGB colors. Can result
  22224. * in a more natural and visually appealing image with enhanced color depth
  22225. * compared to {@link ColorAdjustment#saturation}.
  22226. *
  22227. * @method
  22228. * @param {Node<vec3>} color - The input color.
  22229. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  22230. * @return {Node<vec3>} The updated color.
  22231. */
  22232. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  22233. const average = add( color.r, color.g, color.b ).div( 3.0 );
  22234. const mx = color.r.max( color.g.max( color.b ) );
  22235. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  22236. return mix( color.rgb, mx, amt );
  22237. } );
  22238. /**
  22239. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  22240. *
  22241. * @method
  22242. * @param {Node<vec3>} color - The input color.
  22243. * @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.
  22244. * @return {Node<vec3>} The updated color.
  22245. */
  22246. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  22247. const k = vec3( 0.57735, 0.57735, 0.57735 );
  22248. const cosAngle = adjustment.cos();
  22249. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  22250. } );
  22251. /**
  22252. * Computes the luminance for the given RGB color value.
  22253. *
  22254. * @method
  22255. * @param {Node<vec3>} color - The color value to compute the luminance for.
  22256. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  22257. * @return {Node<vec3>} The luminance.
  22258. */
  22259. const luminance = (
  22260. color,
  22261. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  22262. ) => dot( color, luminanceCoefficients );
  22263. /**
  22264. * Color Decision List (CDL) v1.2
  22265. *
  22266. * Compact representation of color grading information, defined by slope, offset, power, and
  22267. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  22268. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  22269. *
  22270. * @method
  22271. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  22272. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  22273. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  22274. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  22275. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  22276. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  22277. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  22278. *
  22279. * References:
  22280. * - ASC CDL v1.2
  22281. * - {@link https://blender.stackexchange.com/a/55239/43930}
  22282. * - {@link https://docs.acescentral.com/specifications/acescc/}
  22283. */
  22284. const cdl = /*@__PURE__*/ Fn( ( [
  22285. color,
  22286. slope = vec3( 1 ),
  22287. offset = vec3( 0 ),
  22288. power = vec3( 1 ),
  22289. saturation = float( 1 ),
  22290. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  22291. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  22292. ] ) => {
  22293. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  22294. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  22295. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  22296. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  22297. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  22298. const pv = v.pow( power ).toVar();
  22299. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  22300. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  22301. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  22302. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  22303. return vec4( v.rgb, color.a );
  22304. } );
  22305. /** @module PosterizeNode **/
  22306. /**
  22307. * Represents a posterize effect which reduces the number of colors
  22308. * in an image, resulting in a more blocky and stylized appearance.
  22309. *
  22310. * @augments TempNode
  22311. */
  22312. class PosterizeNode extends TempNode {
  22313. static get type() {
  22314. return 'PosterizeNode';
  22315. }
  22316. /**
  22317. * Constructs a new posterize node.
  22318. *
  22319. * @param {Node} sourceNode - The input color.
  22320. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22321. */
  22322. constructor( sourceNode, stepsNode ) {
  22323. super();
  22324. /**
  22325. * The input color.
  22326. *
  22327. * @type {Node}
  22328. */
  22329. this.sourceNode = sourceNode;
  22330. /**
  22331. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22332. *
  22333. * @type {Node}
  22334. */
  22335. this.stepsNode = stepsNode;
  22336. }
  22337. setup() {
  22338. const { sourceNode, stepsNode } = this;
  22339. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  22340. }
  22341. }
  22342. /**
  22343. * TSL function for creating a posterize node.
  22344. *
  22345. * @function
  22346. * @param {Node} sourceNode - The input color.
  22347. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  22348. * @returns {PosterizeNode}
  22349. */
  22350. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  22351. /** @module PassNode **/
  22352. const _size = /*@__PURE__*/ new Vector2();
  22353. /**
  22354. * Represents the texture of a pass node.
  22355. *
  22356. * @augments module:TextureNode~TextureNode
  22357. */
  22358. class PassTextureNode extends TextureNode {
  22359. static get type() {
  22360. return 'PassTextureNode';
  22361. }
  22362. /**
  22363. * Constructs a new pass texture node.
  22364. *
  22365. * @param {PassNode} passNode - The pass node.
  22366. * @param {Texture} texture - The output texture.
  22367. */
  22368. constructor( passNode, texture ) {
  22369. super( texture );
  22370. /**
  22371. * A reference to the pass node.
  22372. *
  22373. * @type {PassNode}
  22374. */
  22375. this.passNode = passNode;
  22376. this.setUpdateMatrix( false );
  22377. }
  22378. setup( builder ) {
  22379. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  22380. return super.setup( builder );
  22381. }
  22382. clone() {
  22383. return new this.constructor( this.passNode, this.value );
  22384. }
  22385. }
  22386. /**
  22387. * An extension of `PassTextureNode` which allows to manage more than one
  22388. * internal texture. Relevant for the `getPreviousTexture()` related API.
  22389. *
  22390. * @augments module:PassTextureNode~PassTextureNode
  22391. */
  22392. class PassMultipleTextureNode extends PassTextureNode {
  22393. static get type() {
  22394. return 'PassMultipleTextureNode';
  22395. }
  22396. /**
  22397. * Constructs a new pass texture node.
  22398. *
  22399. * @param {PassNode} passNode - The pass node.
  22400. * @param {String} textureName - The output texture name.
  22401. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  22402. */
  22403. constructor( passNode, textureName, previousTexture = false ) {
  22404. // null is passed to the super call since this class does not
  22405. // use an external texture for rendering pass data into. Instead
  22406. // the texture is managed by the pass node itself
  22407. super( passNode, null );
  22408. /**
  22409. * The output texture name.
  22410. *
  22411. * @type {String}
  22412. */
  22413. this.textureName = textureName;
  22414. /**
  22415. * Whether previous frame data should be used or not.
  22416. *
  22417. * @type {Boolean}
  22418. */
  22419. this.previousTexture = previousTexture;
  22420. }
  22421. /**
  22422. * Updates the texture reference of this node.
  22423. */
  22424. updateTexture() {
  22425. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  22426. }
  22427. setup( builder ) {
  22428. this.updateTexture();
  22429. return super.setup( builder );
  22430. }
  22431. clone() {
  22432. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  22433. }
  22434. }
  22435. /**
  22436. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  22437. * This pass produces a render for the given scene and camera and can provide multiple outputs
  22438. * via MRT for further processing.
  22439. *
  22440. * ```js
  22441. * const postProcessing = new PostProcessing( renderer );
  22442. *
  22443. * const scenePass = pass( scene, camera );
  22444. *
  22445. * postProcessing.outputNode = scenePass;
  22446. * ```
  22447. *
  22448. * @augments TempNode
  22449. */
  22450. class PassNode extends TempNode {
  22451. static get type() {
  22452. return 'PassNode';
  22453. }
  22454. /**
  22455. * Constructs a new pass node.
  22456. *
  22457. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  22458. * @param {Scene} scene - A reference to the scene.
  22459. * @param {Camera} camera - A reference to the camera.
  22460. * @param {Object} options - Options for the internal render target.
  22461. */
  22462. constructor( scope, scene, camera, options = {} ) {
  22463. super( 'vec4' );
  22464. /**
  22465. * The scope of the pass. The scope determines whether the node outputs color or depth.
  22466. *
  22467. * @type {('color'|'depth')}
  22468. */
  22469. this.scope = scope;
  22470. /**
  22471. * A reference to the scene.
  22472. *
  22473. * @type {Scene}
  22474. */
  22475. this.scene = scene;
  22476. /**
  22477. * A reference to the camera.
  22478. *
  22479. * @type {Camera}
  22480. */
  22481. this.camera = camera;
  22482. /**
  22483. * Options for the internal render target.
  22484. *
  22485. * @type {Object}
  22486. */
  22487. this.options = options;
  22488. /**
  22489. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  22490. *
  22491. * @private
  22492. * @type {Number}
  22493. * @default 1
  22494. */
  22495. this._pixelRatio = 1;
  22496. /**
  22497. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  22498. * @private
  22499. * @type {Number}
  22500. * @default 1
  22501. */
  22502. this._width = 1;
  22503. /**
  22504. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  22505. * @private
  22506. * @type {Number}
  22507. * @default 1
  22508. */
  22509. this._height = 1;
  22510. const depthTexture = new DepthTexture();
  22511. depthTexture.isRenderTargetTexture = true;
  22512. //depthTexture.type = FloatType;
  22513. depthTexture.name = 'depth';
  22514. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  22515. renderTarget.texture.name = 'output';
  22516. renderTarget.depthTexture = depthTexture;
  22517. /**
  22518. * The pass's render target.
  22519. *
  22520. * @type {RenderTarget}
  22521. */
  22522. this.renderTarget = renderTarget;
  22523. /**
  22524. * A dictionary holding the internal result textures.
  22525. *
  22526. * @private
  22527. * @type {Object<String, Texture>}
  22528. */
  22529. this._textures = {
  22530. output: renderTarget.texture,
  22531. depth: depthTexture
  22532. };
  22533. /**
  22534. * A dictionary holding the internal texture nodes.
  22535. *
  22536. * @private
  22537. * @type {Object<String, TextureNode>}
  22538. */
  22539. this._textureNodes = {};
  22540. /**
  22541. * A dictionary holding the internal depth nodes.
  22542. *
  22543. * @private
  22544. * @type {Object}
  22545. */
  22546. this._linearDepthNodes = {};
  22547. /**
  22548. * A dictionary holding the internal viewZ nodes.
  22549. *
  22550. * @private
  22551. * @type {Object}
  22552. */
  22553. this._viewZNodes = {};
  22554. /**
  22555. * A dictionary holding the texture data of the previous frame.
  22556. * Used for computing velocity/motion vectors.
  22557. *
  22558. * @private
  22559. * @type {Object<String, Texture>}
  22560. */
  22561. this._previousTextures = {};
  22562. /**
  22563. * A dictionary holding the texture nodes of the previous frame.
  22564. * Used for computing velocity/motion vectors.
  22565. *
  22566. * @private
  22567. * @type {Object<String, TextureNode>}
  22568. */
  22569. this._previousTextureNodes = {};
  22570. /**
  22571. * The `near` property of the camera as a uniform.
  22572. *
  22573. * @private
  22574. * @type {UniformNode}
  22575. */
  22576. this._cameraNear = uniform( 0 );
  22577. /**
  22578. * The `far` property of the camera as a uniform.
  22579. *
  22580. * @private
  22581. * @type {UniformNode}
  22582. */
  22583. this._cameraFar = uniform( 0 );
  22584. /**
  22585. * A MRT node configuring the MRT settings.
  22586. *
  22587. * @private
  22588. * @type {MRTNode?}
  22589. * @default null
  22590. */
  22591. this._mrt = null;
  22592. /**
  22593. * This flag can be used for type testing.
  22594. *
  22595. * @type {Boolean}
  22596. * @readonly
  22597. * @default true
  22598. */
  22599. this.isPassNode = true;
  22600. /**
  22601. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  22602. * scene once per frame in its {@link PassNode#updateBefore} method.
  22603. *
  22604. * @type {String}
  22605. * @default 'frame'
  22606. */
  22607. this.updateBeforeType = NodeUpdateType.FRAME;
  22608. }
  22609. /**
  22610. * Sets the given MRT node to setup MRT for this pass.
  22611. *
  22612. * @param {MRTNode} mrt - The MRT object.
  22613. * @return {PassNode} A reference to this pass.
  22614. */
  22615. setMRT( mrt ) {
  22616. this._mrt = mrt;
  22617. return this;
  22618. }
  22619. /**
  22620. * Returns the current MRT node.
  22621. *
  22622. * @return {MRTNode} The current MRT node.
  22623. */
  22624. getMRT() {
  22625. return this._mrt;
  22626. }
  22627. /**
  22628. * The method is overwritten so it always returns `true`.
  22629. *
  22630. * @return {Boolean} Whether this node is global or not.
  22631. */
  22632. isGlobal() {
  22633. return true;
  22634. }
  22635. /**
  22636. * Returns the texture for the given output name.
  22637. *
  22638. * @param {String} name - The output name to get the texture for.
  22639. * @return {Texture} The texture.
  22640. */
  22641. getTexture( name ) {
  22642. let texture = this._textures[ name ];
  22643. if ( texture === undefined ) {
  22644. const refTexture = this.renderTarget.texture;
  22645. texture = refTexture.clone();
  22646. texture.name = name;
  22647. this._textures[ name ] = texture;
  22648. this.renderTarget.textures.push( texture );
  22649. }
  22650. return texture;
  22651. }
  22652. /**
  22653. * Returns the texture holding the data of the previous frame for the given output name.
  22654. *
  22655. * @param {String} name - The output name to get the texture for.
  22656. * @return {Texture} The texture holding the data of the previous frame.
  22657. */
  22658. getPreviousTexture( name ) {
  22659. let texture = this._previousTextures[ name ];
  22660. if ( texture === undefined ) {
  22661. texture = this.getTexture( name ).clone();
  22662. this._previousTextures[ name ] = texture;
  22663. }
  22664. return texture;
  22665. }
  22666. /**
  22667. * Switches current and previous textures for the given output name.
  22668. *
  22669. * @param {String} name - The output name.
  22670. */
  22671. toggleTexture( name ) {
  22672. const prevTexture = this._previousTextures[ name ];
  22673. if ( prevTexture !== undefined ) {
  22674. const texture = this._textures[ name ];
  22675. const index = this.renderTarget.textures.indexOf( texture );
  22676. this.renderTarget.textures[ index ] = prevTexture;
  22677. this._textures[ name ] = prevTexture;
  22678. this._previousTextures[ name ] = texture;
  22679. this._textureNodes[ name ].updateTexture();
  22680. this._previousTextureNodes[ name ].updateTexture();
  22681. }
  22682. }
  22683. /**
  22684. * Returns the texture node for the given output name.
  22685. *
  22686. * @param {String} [name='output'] - The output name to get the texture node for.
  22687. * @return {TextureNode} The texture node.
  22688. */
  22689. getTextureNode( name = 'output' ) {
  22690. let textureNode = this._textureNodes[ name ];
  22691. if ( textureNode === undefined ) {
  22692. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22693. textureNode.updateTexture();
  22694. this._textureNodes[ name ] = textureNode;
  22695. }
  22696. return textureNode;
  22697. }
  22698. /**
  22699. * Returns the previous texture node for the given output name.
  22700. *
  22701. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22702. * @return {TextureNode} The previous texture node.
  22703. */
  22704. getPreviousTextureNode( name = 'output' ) {
  22705. let textureNode = this._previousTextureNodes[ name ];
  22706. if ( textureNode === undefined ) {
  22707. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22708. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22709. textureNode.updateTexture();
  22710. this._previousTextureNodes[ name ] = textureNode;
  22711. }
  22712. return textureNode;
  22713. }
  22714. /**
  22715. * Returns a viewZ node of this pass.
  22716. *
  22717. * @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.
  22718. * @return {Node} The viewZ node.
  22719. */
  22720. getViewZNode( name = 'depth' ) {
  22721. let viewZNode = this._viewZNodes[ name ];
  22722. if ( viewZNode === undefined ) {
  22723. const cameraNear = this._cameraNear;
  22724. const cameraFar = this._cameraFar;
  22725. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22726. }
  22727. return viewZNode;
  22728. }
  22729. /**
  22730. * Returns a linear depth node of this pass.
  22731. *
  22732. * @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.
  22733. * @return {Node} The linear depth node.
  22734. */
  22735. getLinearDepthNode( name = 'depth' ) {
  22736. let linearDepthNode = this._linearDepthNodes[ name ];
  22737. if ( linearDepthNode === undefined ) {
  22738. const cameraNear = this._cameraNear;
  22739. const cameraFar = this._cameraFar;
  22740. const viewZNode = this.getViewZNode( name );
  22741. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22742. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22743. }
  22744. return linearDepthNode;
  22745. }
  22746. setup( { renderer } ) {
  22747. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22748. // TODO: Disable MSAA for WebGL backend for now
  22749. if ( renderer.backend.isWebGLBackend === true ) {
  22750. this.renderTarget.samples = 0;
  22751. }
  22752. this.renderTarget.texture.type = renderer.getColorBufferType();
  22753. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22754. }
  22755. updateBefore( frame ) {
  22756. const { renderer } = frame;
  22757. const { scene, camera } = this;
  22758. this._pixelRatio = renderer.getPixelRatio();
  22759. const size = renderer.getSize( _size );
  22760. this.setSize( size.width, size.height );
  22761. const currentRenderTarget = renderer.getRenderTarget();
  22762. const currentMRT = renderer.getMRT();
  22763. this._cameraNear.value = camera.near;
  22764. this._cameraFar.value = camera.far;
  22765. for ( const name in this._previousTextures ) {
  22766. this.toggleTexture( name );
  22767. }
  22768. renderer.setRenderTarget( this.renderTarget );
  22769. renderer.setMRT( this._mrt );
  22770. renderer.render( scene, camera );
  22771. renderer.setRenderTarget( currentRenderTarget );
  22772. renderer.setMRT( currentMRT );
  22773. }
  22774. /**
  22775. * Sets the size of the pass's render target. Honors the pixel ratio.
  22776. *
  22777. * @param {Number} width - The width to set.
  22778. * @param {Number} height - The height to set.
  22779. */
  22780. setSize( width, height ) {
  22781. this._width = width;
  22782. this._height = height;
  22783. const effectiveWidth = this._width * this._pixelRatio;
  22784. const effectiveHeight = this._height * this._pixelRatio;
  22785. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22786. }
  22787. /**
  22788. * Sets the pixel ratio the pass's render target and updates the size.
  22789. *
  22790. * @param {Number} pixelRatio - The pixel ratio to set.
  22791. */
  22792. setPixelRatio( pixelRatio ) {
  22793. this._pixelRatio = pixelRatio;
  22794. this.setSize( this._width, this._height );
  22795. }
  22796. /**
  22797. * Frees internal resources. Should be called when the node is no longer in use.
  22798. */
  22799. dispose() {
  22800. this.renderTarget.dispose();
  22801. }
  22802. }
  22803. PassNode.COLOR = 'color';
  22804. PassNode.DEPTH = 'depth';
  22805. /**
  22806. * TSL function for creating a pass node.
  22807. *
  22808. * @function
  22809. * @param {Scene} scene - A reference to the scene.
  22810. * @param {Camera} camera - A reference to the camera.
  22811. * @param {Object} options - Options for the internal render target.
  22812. * @returns {PassNode}
  22813. */
  22814. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22815. /**
  22816. * TSL function for creating a pass texture node.
  22817. *
  22818. * @function
  22819. * @param {PassNode} pass - The pass node.
  22820. * @param {Texture} texture - The output texture.
  22821. * @returns {PassTextureNode}
  22822. */
  22823. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22824. /**
  22825. * TSL function for creating a depth pass node.
  22826. *
  22827. * @function
  22828. * @param {Scene} scene - A reference to the scene.
  22829. * @param {Camera} camera - A reference to the camera.
  22830. * @param {Object} options - Options for the internal render target.
  22831. * @returns {PassNode}
  22832. */
  22833. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22834. /** @module ToonOutlinePassNode **/
  22835. /**
  22836. * Represents a render pass for producing a toon outline effect on compatible objects.
  22837. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22838. * will receive the outline.
  22839. *
  22840. * ```js
  22841. * const postProcessing = new PostProcessing( renderer );
  22842. *
  22843. * const scenePass = toonOutlinePass( scene, camera );
  22844. *
  22845. * postProcessing.outputNode = scenePass;
  22846. * ```
  22847. * @augments PassNode
  22848. */
  22849. class ToonOutlinePassNode extends PassNode {
  22850. static get type() {
  22851. return 'ToonOutlinePassNode';
  22852. }
  22853. /**
  22854. * Constructs a new outline pass node.
  22855. *
  22856. * @param {Scene} scene - A reference to the scene.
  22857. * @param {Camera} camera - A reference to the camera.
  22858. * @param {Node} colorNode - Defines the outline's color.
  22859. * @param {Node} thicknessNode - Defines the outline's thickness.
  22860. * @param {Node} alphaNode - Defines the outline's alpha.
  22861. */
  22862. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22863. super( PassNode.COLOR, scene, camera );
  22864. /**
  22865. * Defines the outline's color.
  22866. *
  22867. * @type {Node}
  22868. */
  22869. this.colorNode = colorNode;
  22870. /**
  22871. * Defines the outline's thickness.
  22872. *
  22873. * @type {Node}
  22874. */
  22875. this.thicknessNode = thicknessNode;
  22876. /**
  22877. * Defines the outline's alpha.
  22878. *
  22879. * @type {Node}
  22880. */
  22881. this.alphaNode = alphaNode;
  22882. /**
  22883. * An internal material cache.
  22884. *
  22885. * @private
  22886. * @type {WeakMap<Material, NodeMaterial>}
  22887. */
  22888. this._materialCache = new WeakMap();
  22889. }
  22890. updateBefore( frame ) {
  22891. const { renderer } = frame;
  22892. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22893. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22894. // only render outline for supported materials
  22895. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22896. if ( material.wireframe === false ) {
  22897. const outlineMaterial = this._getOutlineMaterial( material );
  22898. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22899. }
  22900. }
  22901. // default
  22902. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22903. } );
  22904. super.updateBefore( frame );
  22905. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22906. }
  22907. /**
  22908. * Creates the material used for outline rendering.
  22909. *
  22910. * @private
  22911. * @return {NodeMaterial} The outline material.
  22912. */
  22913. _createMaterial() {
  22914. const material = new NodeMaterial();
  22915. material.isMeshToonOutlineMaterial = true;
  22916. material.name = 'Toon_Outline';
  22917. material.side = BackSide;
  22918. // vertex node
  22919. const outlineNormal = normalLocal.negate();
  22920. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22921. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22922. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22923. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22924. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22925. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22926. // color node
  22927. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22928. return material;
  22929. }
  22930. /**
  22931. * For the given toon material, this method returns a corresponding
  22932. * outline material.
  22933. *
  22934. * @private
  22935. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22936. * @return {NodeMaterial} The outline material.
  22937. */
  22938. _getOutlineMaterial( originalMaterial ) {
  22939. let outlineMaterial = this._materialCache.get( originalMaterial );
  22940. if ( outlineMaterial === undefined ) {
  22941. outlineMaterial = this._createMaterial();
  22942. this._materialCache.set( originalMaterial, outlineMaterial );
  22943. }
  22944. return outlineMaterial;
  22945. }
  22946. }
  22947. /**
  22948. * TSL function for creating a toon outline pass node.
  22949. *
  22950. * @function
  22951. * @param {Scene} scene - A reference to the scene.
  22952. * @param {Camera} camera - A reference to the camera.
  22953. * @param {Color} color - Defines the outline's color.
  22954. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22955. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22956. * @returns {ToonOutlinePassNode}
  22957. */
  22958. 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 ) ) );
  22959. /** @module ToneMappingFunctions **/
  22960. /**
  22961. * Linear tone mapping, exposure only.
  22962. *
  22963. * @method
  22964. * @param {Node<vec3>} color - The color that should be tone mapped.
  22965. * @param {Node<float>} exposure - The exposure.
  22966. * @return {Node<vec3>} The tone mapped color.
  22967. */
  22968. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22969. return color.mul( exposure ).clamp();
  22970. } ).setLayout( {
  22971. name: 'linearToneMapping',
  22972. type: 'vec3',
  22973. inputs: [
  22974. { name: 'color', type: 'vec3' },
  22975. { name: 'exposure', type: 'float' }
  22976. ]
  22977. } );
  22978. /**
  22979. * Reinhard tone mapping.
  22980. *
  22981. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22982. *
  22983. * @method
  22984. * @param {Node<vec3>} color - The color that should be tone mapped.
  22985. * @param {Node<float>} exposure - The exposure.
  22986. * @return {Node<vec3>} The tone mapped color.
  22987. */
  22988. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22989. color = color.mul( exposure );
  22990. return color.div( color.add( 1.0 ) ).clamp();
  22991. } ).setLayout( {
  22992. name: 'reinhardToneMapping',
  22993. type: 'vec3',
  22994. inputs: [
  22995. { name: 'color', type: 'vec3' },
  22996. { name: 'exposure', type: 'float' }
  22997. ]
  22998. } );
  22999. /**
  23000. * Cineon tone mapping.
  23001. *
  23002. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  23003. *
  23004. * @method
  23005. * @param {Node<vec3>} color - The color that should be tone mapped.
  23006. * @param {Node<float>} exposure - The exposure.
  23007. * @return {Node<vec3>} The tone mapped color.
  23008. */
  23009. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23010. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  23011. color = color.mul( exposure );
  23012. color = color.sub( 0.004 ).max( 0.0 );
  23013. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  23014. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  23015. return a.div( b ).pow( 2.2 );
  23016. } ).setLayout( {
  23017. name: 'cineonToneMapping',
  23018. type: 'vec3',
  23019. inputs: [
  23020. { name: 'color', type: 'vec3' },
  23021. { name: 'exposure', type: 'float' }
  23022. ]
  23023. } );
  23024. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  23025. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23026. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  23027. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  23028. return a.div( b );
  23029. } );
  23030. /**
  23031. * ACESFilmic tone mapping.
  23032. *
  23033. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  23034. *
  23035. * @method
  23036. * @param {Node<vec3>} color - The color that should be tone mapped.
  23037. * @param {Node<float>} exposure - The exposure.
  23038. * @return {Node<vec3>} The tone mapped color.
  23039. */
  23040. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23041. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  23042. const ACESInputMat = mat3(
  23043. 0.59719, 0.35458, 0.04823,
  23044. 0.07600, 0.90834, 0.01566,
  23045. 0.02840, 0.13383, 0.83777
  23046. );
  23047. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  23048. const ACESOutputMat = mat3(
  23049. 1.60475, - 0.53108, - 0.07367,
  23050. - 0.10208, 1.10813, - 0.00605,
  23051. - 0.00327, - 0.07276, 1.07602
  23052. );
  23053. color = color.mul( exposure ).div( 0.6 );
  23054. color = ACESInputMat.mul( color );
  23055. // Apply RRT and ODT
  23056. color = RRTAndODTFit( color );
  23057. color = ACESOutputMat.mul( color );
  23058. // Clamp to [0, 1]
  23059. return color.clamp();
  23060. } ).setLayout( {
  23061. name: 'acesFilmicToneMapping',
  23062. type: 'vec3',
  23063. inputs: [
  23064. { name: 'color', type: 'vec3' },
  23065. { name: 'exposure', type: 'float' }
  23066. ]
  23067. } );
  23068. 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, - 0.0083, 1.1187 ) );
  23069. 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 ) );
  23070. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  23071. const x = vec3( x_immutable ).toVar();
  23072. const x2 = vec3( x.mul( x ) ).toVar();
  23073. const x4 = vec3( x2.mul( x2 ) ).toVar();
  23074. 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 ) ) ) );
  23075. } );
  23076. /**
  23077. * AgX tone mapping.
  23078. *
  23079. * @method
  23080. * @param {Node<vec3>} color - The color that should be tone mapped.
  23081. * @param {Node<float>} exposure - The exposure.
  23082. * @return {Node<vec3>} The tone mapped color.
  23083. */
  23084. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23085. const colortone = vec3( color ).toVar();
  23086. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  23087. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  23088. const AgxMinEv = float( - 12.47393 );
  23089. const AgxMaxEv = float( 4.026069 );
  23090. colortone.mulAssign( exposure );
  23091. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  23092. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  23093. colortone.assign( max$1( colortone, 1e-10 ) );
  23094. colortone.assign( log2( colortone ) );
  23095. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  23096. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  23097. colortone.assign( agxDefaultContrastApprox( colortone ) );
  23098. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  23099. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  23100. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  23101. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  23102. return colortone;
  23103. } ).setLayout( {
  23104. name: 'agxToneMapping',
  23105. type: 'vec3',
  23106. inputs: [
  23107. { name: 'color', type: 'vec3' },
  23108. { name: 'exposure', type: 'float' }
  23109. ]
  23110. } );
  23111. /**
  23112. * Neutral tone mapping.
  23113. *
  23114. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  23115. *
  23116. * @method
  23117. * @param {Node<vec3>} color - The color that should be tone mapped.
  23118. * @param {Node<float>} exposure - The exposure.
  23119. * @return {Node<vec3>} The tone mapped color.
  23120. */
  23121. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  23122. const StartCompression = float( 0.8 - 0.04 );
  23123. const Desaturation = float( 0.15 );
  23124. color = color.mul( exposure );
  23125. const x = min$1( color.r, min$1( color.g, color.b ) );
  23126. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  23127. color.subAssign( offset );
  23128. const peak = max$1( color.r, max$1( color.g, color.b ) );
  23129. If( peak.lessThan( StartCompression ), () => {
  23130. return color;
  23131. } );
  23132. const d = sub( 1, StartCompression );
  23133. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  23134. color.mulAssign( newPeak.div( peak ) );
  23135. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  23136. return mix( color, vec3( newPeak ), g );
  23137. } ).setLayout( {
  23138. name: 'neutralToneMapping',
  23139. type: 'vec3',
  23140. inputs: [
  23141. { name: 'color', type: 'vec3' },
  23142. { name: 'exposure', type: 'float' }
  23143. ]
  23144. } );
  23145. /** @module CodeNode **/
  23146. /**
  23147. * This class represents native code sections. It is the base
  23148. * class for modules like {@link FunctionNode} which allows to implement
  23149. * functions with native shader languages.
  23150. *
  23151. * @augments Node
  23152. */
  23153. class CodeNode extends Node {
  23154. static get type() {
  23155. return 'CodeNode';
  23156. }
  23157. /**
  23158. * Constructs a new code node.
  23159. *
  23160. * @param {String} [code=''] - The native code.
  23161. * @param {Array<Node>} [includes=[]] - An array of includes.
  23162. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23163. */
  23164. constructor( code = '', includes = [], language = '' ) {
  23165. super( 'code' );
  23166. /**
  23167. * This flag can be used for type testing.
  23168. *
  23169. * @type {Boolean}
  23170. * @readonly
  23171. * @default true
  23172. */
  23173. this.isCodeNode = true;
  23174. /**
  23175. * The native code.
  23176. *
  23177. * @type {String}
  23178. * @default ''
  23179. */
  23180. this.code = code;
  23181. /**
  23182. * An array of includes
  23183. *
  23184. * @type {Array<Node>}
  23185. * @default []
  23186. */
  23187. this.includes = includes;
  23188. /**
  23189. * The used language.
  23190. *
  23191. * @type {('js'|'wgsl'|'glsl')}
  23192. * @default ''
  23193. */
  23194. this.language = language;
  23195. }
  23196. /**
  23197. * The method is overwritten so it always returns `true`.
  23198. *
  23199. * @return {Boolean} Whether this node is global or not.
  23200. */
  23201. isGlobal() {
  23202. return true;
  23203. }
  23204. /**
  23205. * Sets the includes of this code node.
  23206. *
  23207. * @param {Array<Node>} includes - The includes to set.
  23208. * @return {CodeNode} A reference to this node.
  23209. */
  23210. setIncludes( includes ) {
  23211. this.includes = includes;
  23212. return this;
  23213. }
  23214. /**
  23215. * Returns the includes of this code node.
  23216. *
  23217. * @param {NodeBuilder} builder - The current node builder.
  23218. * @return {Array<Node>} The includes.
  23219. */
  23220. getIncludes( /*builder*/ ) {
  23221. return this.includes;
  23222. }
  23223. generate( builder ) {
  23224. const includes = this.getIncludes( builder );
  23225. for ( const include of includes ) {
  23226. include.build( builder );
  23227. }
  23228. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  23229. nodeCode.code = this.code;
  23230. return nodeCode.code;
  23231. }
  23232. serialize( data ) {
  23233. super.serialize( data );
  23234. data.code = this.code;
  23235. data.language = this.language;
  23236. }
  23237. deserialize( data ) {
  23238. super.deserialize( data );
  23239. this.code = data.code;
  23240. this.language = data.language;
  23241. }
  23242. }
  23243. /**
  23244. * TSL function for creating a code node.
  23245. *
  23246. * @function
  23247. * @param {String} [code=''] - The native code.
  23248. * @param {Array<Node>} [includes=[]] - An array of includes.
  23249. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23250. * @returns {CodeNode}
  23251. */
  23252. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  23253. /**
  23254. * TSL function for creating a JS code node.
  23255. *
  23256. * @function
  23257. * @param {String} src - The native code.
  23258. * @param {Array<Node>} includes - An array of includes.
  23259. * @returns {CodeNode}
  23260. */
  23261. const js = ( src, includes ) => code( src, includes, 'js' );
  23262. /**
  23263. * TSL function for creating a WGSL code node.
  23264. *
  23265. * @function
  23266. * @param {String} src - The native code.
  23267. * @param {Array<Node>} includes - An array of includes.
  23268. * @returns {CodeNode}
  23269. */
  23270. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  23271. /**
  23272. * TSL function for creating a GLSL code node.
  23273. *
  23274. * @function
  23275. * @param {String} src - The native code.
  23276. * @param {Array<Node>} includes - An array of includes.
  23277. * @returns {CodeNode}
  23278. */
  23279. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  23280. /**
  23281. * This class represents a native shader function. It can be used to implement
  23282. * certain aspects of a node material with native shader code. There are two predefined
  23283. * TSL functions for easier usage.
  23284. *
  23285. * - `wgslFn`: Creates a WGSL function node.
  23286. * - `glslFn`: Creates a GLSL function node.
  23287. *
  23288. * A basic example with one include looks like so:
  23289. *
  23290. * ```js
  23291. * const desaturateWGSLFn = wgslFn( `
  23292. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  23293. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  23294. * return vec3<f32>( dot( lum, color ) );
  23295. * }`
  23296. *);
  23297. * const someWGSLFn = wgslFn( `
  23298. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  23299. * return desaturate( color );
  23300. * }
  23301. * `, [ desaturateWGSLFn ] );
  23302. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  23303. *```
  23304. * @augments CodeNode
  23305. */
  23306. class FunctionNode extends CodeNode {
  23307. static get type() {
  23308. return 'FunctionNode';
  23309. }
  23310. /**
  23311. * Constructs a new function node.
  23312. *
  23313. * @param {String} [code=''] - The native code.
  23314. * @param {Array<Node>} [includes=[]] - An array of includes.
  23315. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  23316. */
  23317. constructor( code = '', includes = [], language = '' ) {
  23318. super( code, includes, language );
  23319. }
  23320. getNodeType( builder ) {
  23321. return this.getNodeFunction( builder ).type;
  23322. }
  23323. /**
  23324. * Returns the inputs of this function node.
  23325. *
  23326. * @param {NodeBuilder} builder - The current node builder.
  23327. * @return {Array<NodeFunctionInput>} The inputs.
  23328. */
  23329. getInputs( builder ) {
  23330. return this.getNodeFunction( builder ).inputs;
  23331. }
  23332. /**
  23333. * Returns the node function for this function node.
  23334. *
  23335. * @param {NodeBuilder} builder - The current node builder.
  23336. * @return {NodeFunction} The node function.
  23337. */
  23338. getNodeFunction( builder ) {
  23339. const nodeData = builder.getDataFromNode( this );
  23340. let nodeFunction = nodeData.nodeFunction;
  23341. if ( nodeFunction === undefined ) {
  23342. nodeFunction = builder.parser.parseFunction( this.code );
  23343. nodeData.nodeFunction = nodeFunction;
  23344. }
  23345. return nodeFunction;
  23346. }
  23347. generate( builder, output ) {
  23348. super.generate( builder );
  23349. const nodeFunction = this.getNodeFunction( builder );
  23350. const name = nodeFunction.name;
  23351. const type = nodeFunction.type;
  23352. const nodeCode = builder.getCodeFromNode( this, type );
  23353. if ( name !== '' ) {
  23354. // use a custom property name
  23355. nodeCode.name = name;
  23356. }
  23357. const propertyName = builder.getPropertyName( nodeCode );
  23358. const code = this.getNodeFunction( builder ).getCode( propertyName );
  23359. nodeCode.code = code + '\n';
  23360. if ( output === 'property' ) {
  23361. return propertyName;
  23362. } else {
  23363. return builder.format( `${ propertyName }()`, type, output );
  23364. }
  23365. }
  23366. }
  23367. const nativeFn = ( code, includes = [], language = '' ) => {
  23368. for ( let i = 0; i < includes.length; i ++ ) {
  23369. const include = includes[ i ];
  23370. // TSL Function: glslFn, wgslFn
  23371. if ( typeof include === 'function' ) {
  23372. includes[ i ] = include.functionNode;
  23373. }
  23374. }
  23375. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  23376. const fn = ( ...params ) => functionNode.call( ...params );
  23377. fn.functionNode = functionNode;
  23378. return fn;
  23379. };
  23380. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23381. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23382. /** @module ScriptableValueNode **/
  23383. /**
  23384. * `ScriptableNode` uses this class to manage script inputs and outputs.
  23385. *
  23386. * @augments Node
  23387. */
  23388. class ScriptableValueNode extends Node {
  23389. static get type() {
  23390. return 'ScriptableValueNode';
  23391. }
  23392. /**
  23393. * Constructs a new scriptable node.
  23394. *
  23395. * @param {Any} [value=null] - The value.
  23396. */
  23397. constructor( value = null ) {
  23398. super();
  23399. /**
  23400. * A reference to the value.
  23401. *
  23402. * @private
  23403. * @default null
  23404. */
  23405. this._value = value;
  23406. /**
  23407. * Depending on the type of `_value`, this property might cache parsed data.
  23408. *
  23409. * @private
  23410. * @default null
  23411. */
  23412. this._cache = null;
  23413. /**
  23414. * If this node represents an input, this property represents the input type.
  23415. *
  23416. * @type {String?}
  23417. * @default null
  23418. */
  23419. this.inputType = null;
  23420. /**
  23421. * If this node represents an output, this property represents the output type.
  23422. *
  23423. * @type {String?}
  23424. * @default null
  23425. */
  23426. this.outputType = null;
  23427. /**
  23428. * An event dispatcher for managing events.
  23429. *
  23430. * @type {EventDispatcher}
  23431. */
  23432. this.events = new EventDispatcher();
  23433. /**
  23434. * This flag can be used for type testing.
  23435. *
  23436. * @type {Boolean}
  23437. * @readonly
  23438. * @default true
  23439. */
  23440. this.isScriptableValueNode = true;
  23441. }
  23442. /**
  23443. * Whether this node represents an output or not.
  23444. *
  23445. * @type {Boolean}
  23446. * @readonly
  23447. * @default true
  23448. */
  23449. get isScriptableOutputNode() {
  23450. return this.outputType !== null;
  23451. }
  23452. set value( val ) {
  23453. if ( this._value === val ) return;
  23454. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  23455. URL.revokeObjectURL( this._cache );
  23456. this._cache = null;
  23457. }
  23458. this._value = val;
  23459. this.events.dispatchEvent( { type: 'change' } );
  23460. this.refresh();
  23461. }
  23462. /**
  23463. * The node's value.
  23464. *
  23465. * @type {Any}
  23466. */
  23467. get value() {
  23468. return this._value;
  23469. }
  23470. /**
  23471. * Dispatches the `refresh` event.
  23472. */
  23473. refresh() {
  23474. this.events.dispatchEvent( { type: 'refresh' } );
  23475. }
  23476. /**
  23477. * The `value` property usually represents a node or even binary data in form of array buffers.
  23478. * In this case, this method tries to return the actual value behind the complex type.
  23479. *
  23480. * @return {Any} The value.
  23481. */
  23482. getValue() {
  23483. const value = this.value;
  23484. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  23485. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  23486. } else if ( value && value.value !== null && value.value !== undefined && (
  23487. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  23488. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  23489. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  23490. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  23491. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  23492. ( this.inputType === 'Color' && value.value.isColor ) ||
  23493. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  23494. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  23495. ) ) {
  23496. return value.value;
  23497. }
  23498. return this._cache || value;
  23499. }
  23500. /**
  23501. * Overwritten since the node type is inferred from the value.
  23502. *
  23503. * @param {NodeBuilder} builder - The current node builder.
  23504. * @return {String} The node type.
  23505. */
  23506. getNodeType( builder ) {
  23507. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  23508. }
  23509. setup() {
  23510. return this.value && this.value.isNode ? this.value : float();
  23511. }
  23512. serialize( data ) {
  23513. super.serialize( data );
  23514. if ( this.value !== null ) {
  23515. if ( this.inputType === 'ArrayBuffer' ) {
  23516. data.value = arrayBufferToBase64( this.value );
  23517. } else {
  23518. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  23519. }
  23520. } else {
  23521. data.value = null;
  23522. }
  23523. data.inputType = this.inputType;
  23524. data.outputType = this.outputType;
  23525. }
  23526. deserialize( data ) {
  23527. super.deserialize( data );
  23528. let value = null;
  23529. if ( data.value !== null ) {
  23530. if ( data.inputType === 'ArrayBuffer' ) {
  23531. value = base64ToArrayBuffer( data.value );
  23532. } else if ( data.inputType === 'Texture' ) {
  23533. value = data.meta.textures[ data.value ];
  23534. } else {
  23535. value = data.meta.nodes[ data.value ] || null;
  23536. }
  23537. }
  23538. this.value = value;
  23539. this.inputType = data.inputType;
  23540. this.outputType = data.outputType;
  23541. }
  23542. }
  23543. /**
  23544. * TSL function for creating a scriptable value node.
  23545. *
  23546. * @function
  23547. * @param {Any} [value=null] - The value.
  23548. * @returns {ScriptableValueNode}
  23549. */
  23550. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  23551. /** @module ScriptableNode **/
  23552. /**
  23553. * A Map-like data structure for managing resources of scriptable nodes.
  23554. *
  23555. * @augments Map
  23556. */
  23557. class Resources extends Map {
  23558. get( key, callback = null, ...params ) {
  23559. if ( this.has( key ) ) return super.get( key );
  23560. if ( callback !== null ) {
  23561. const value = callback( ...params );
  23562. this.set( key, value );
  23563. return value;
  23564. }
  23565. }
  23566. }
  23567. class Parameters {
  23568. constructor( scriptableNode ) {
  23569. this.scriptableNode = scriptableNode;
  23570. }
  23571. get parameters() {
  23572. return this.scriptableNode.parameters;
  23573. }
  23574. get layout() {
  23575. return this.scriptableNode.getLayout();
  23576. }
  23577. getInputLayout( id ) {
  23578. return this.scriptableNode.getInputLayout( id );
  23579. }
  23580. get( name ) {
  23581. const param = this.parameters[ name ];
  23582. const value = param ? param.getValue() : null;
  23583. return value;
  23584. }
  23585. }
  23586. /**
  23587. * Defines the resources (e.g. namespaces) of scriptable nodes.
  23588. *
  23589. * @type {Resources}
  23590. */
  23591. const ScriptableNodeResources = new Resources();
  23592. /**
  23593. * This type of node allows to implement nodes with custom scripts. The script
  23594. * section is represented as an instance of `CodeNode` written with JavaScript.
  23595. * The script itself must adhere to a specific structure.
  23596. *
  23597. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  23598. * - layout: The layout object defines the script's interface (inputs and outputs).
  23599. *
  23600. * ```js
  23601. * ScriptableNodeResources.set( 'TSL', TSL );
  23602. *
  23603. * const scriptableNode = scriptable( js( `
  23604. * layout = {
  23605. * outputType: 'node',
  23606. * elements: [
  23607. * { name: 'source', inputType: 'node' },
  23608. * ]
  23609. * };
  23610. *
  23611. * const { mul, oscSine } = TSL;
  23612. *
  23613. * function main() {
  23614. * const source = parameters.get( 'source' ) || float();
  23615. * return mul( source, oscSine() ) );
  23616. * }
  23617. *
  23618. * ` ) );
  23619. *
  23620. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  23621. *
  23622. * const material = new THREE.MeshBasicNodeMaterial();
  23623. * material.colorNode = scriptableNode;
  23624. * ```
  23625. *
  23626. * @augments Node
  23627. */
  23628. class ScriptableNode extends Node {
  23629. static get type() {
  23630. return 'ScriptableNode';
  23631. }
  23632. /**
  23633. * Constructs a new scriptable node.
  23634. *
  23635. * @param {CodeNode?} [codeNode=null] - The code node.
  23636. * @param {Object} [parameters={}] - The parameters definition.
  23637. */
  23638. constructor( codeNode = null, parameters = {} ) {
  23639. super();
  23640. /**
  23641. * The code node.
  23642. *
  23643. * @type {CodeNode?}
  23644. * @default null
  23645. */
  23646. this.codeNode = codeNode;
  23647. /**
  23648. * The parameters definition.
  23649. *
  23650. * @type {Object}
  23651. * @default {}
  23652. */
  23653. this.parameters = parameters;
  23654. this._local = new Resources();
  23655. this._output = scriptableValue();
  23656. this._outputs = {};
  23657. this._source = this.source;
  23658. this._method = null;
  23659. this._object = null;
  23660. this._value = null;
  23661. this._needsOutputUpdate = true;
  23662. this.onRefresh = this.onRefresh.bind( this );
  23663. /**
  23664. * This flag can be used for type testing.
  23665. *
  23666. * @type {Boolean}
  23667. * @readonly
  23668. * @default true
  23669. */
  23670. this.isScriptableNode = true;
  23671. }
  23672. /**
  23673. * The source code of the scriptable node.
  23674. *
  23675. * @type {String}
  23676. */
  23677. get source() {
  23678. return this.codeNode ? this.codeNode.code : '';
  23679. }
  23680. /**
  23681. * Sets the reference of a local script variable.
  23682. *
  23683. * @param {String} name - The variable name.
  23684. * @param {Object} value - The reference to set.
  23685. * @return {Resources} The resource map
  23686. */
  23687. setLocal( name, value ) {
  23688. return this._local.set( name, value );
  23689. }
  23690. /**
  23691. * Gets the value of a local script variable.
  23692. *
  23693. * @param {String} name - The variable name.
  23694. * @return {Object} The value.
  23695. */
  23696. getLocal( name ) {
  23697. return this._local.get( name );
  23698. }
  23699. /**
  23700. * Event listener for the `refresh` event.
  23701. */
  23702. onRefresh() {
  23703. this._refresh();
  23704. }
  23705. /**
  23706. * Returns an input from the layout with the given id/name.
  23707. *
  23708. * @param {String} id - The id/name of the input.
  23709. * @return {Object} The element entry.
  23710. */
  23711. getInputLayout( id ) {
  23712. for ( const element of this.getLayout() ) {
  23713. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23714. return element;
  23715. }
  23716. }
  23717. }
  23718. /**
  23719. * Returns an output from the layout with the given id/name.
  23720. *
  23721. * @param {String} id - The id/name of the output.
  23722. * @return {Object} The element entry.
  23723. */
  23724. getOutputLayout( id ) {
  23725. for ( const element of this.getLayout() ) {
  23726. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23727. return element;
  23728. }
  23729. }
  23730. }
  23731. /**
  23732. * Defines a script output for the given name and value.
  23733. *
  23734. * @param {String} name - The name of the output.
  23735. * @param {Node} value - The node value.
  23736. * @return {ScriptableNode} A reference to this node.
  23737. */
  23738. setOutput( name, value ) {
  23739. const outputs = this._outputs;
  23740. if ( outputs[ name ] === undefined ) {
  23741. outputs[ name ] = scriptableValue( value );
  23742. } else {
  23743. outputs[ name ].value = value;
  23744. }
  23745. return this;
  23746. }
  23747. /**
  23748. * Returns a script output for the given name.
  23749. *
  23750. * @param {String} name - The name of the output.
  23751. * @return {ScriptableValueNode} The node value.
  23752. */
  23753. getOutput( name ) {
  23754. return this._outputs[ name ];
  23755. }
  23756. /**
  23757. * Returns a parameter for the given name
  23758. *
  23759. * @param {String} name - The name of the parameter.
  23760. * @return {ScriptableValueNode} The node value.
  23761. */
  23762. getParameter( name ) {
  23763. return this.parameters[ name ];
  23764. }
  23765. /**
  23766. * Sets a value for the given parameter name.
  23767. *
  23768. * @param {String} name - The parameter name.
  23769. * @param {Any} value - The parameter value.
  23770. * @return {ScriptableNode} A reference to this node.
  23771. */
  23772. setParameter( name, value ) {
  23773. const parameters = this.parameters;
  23774. if ( value && value.isScriptableNode ) {
  23775. this.deleteParameter( name );
  23776. parameters[ name ] = value;
  23777. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23778. } else if ( value && value.isScriptableValueNode ) {
  23779. this.deleteParameter( name );
  23780. parameters[ name ] = value;
  23781. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23782. } else if ( parameters[ name ] === undefined ) {
  23783. parameters[ name ] = scriptableValue( value );
  23784. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23785. } else {
  23786. parameters[ name ].value = value;
  23787. }
  23788. return this;
  23789. }
  23790. /**
  23791. * Returns the value of this node which is the value of
  23792. * the default output.
  23793. *
  23794. * @return {Node} The value.
  23795. */
  23796. getValue() {
  23797. return this.getDefaultOutput().getValue();
  23798. }
  23799. /**
  23800. * Deletes a parameter from the script.
  23801. *
  23802. * @param {String} name - The parameter to remove.
  23803. * @return {ScriptableNode} A reference to this node.
  23804. */
  23805. deleteParameter( name ) {
  23806. let valueNode = this.parameters[ name ];
  23807. if ( valueNode ) {
  23808. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23809. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23810. }
  23811. return this;
  23812. }
  23813. /**
  23814. * Deletes all parameters from the script.
  23815. *
  23816. * @return {ScriptableNode} A reference to this node.
  23817. */
  23818. clearParameters() {
  23819. for ( const name of Object.keys( this.parameters ) ) {
  23820. this.deleteParameter( name );
  23821. }
  23822. this.needsUpdate = true;
  23823. return this;
  23824. }
  23825. /**
  23826. * Calls a function from the script.
  23827. *
  23828. * @param {String} name - The function name.
  23829. * @param {...Any} params - A list of parameters.
  23830. * @return {Any} The result of the function call.
  23831. */
  23832. call( name, ...params ) {
  23833. const object = this.getObject();
  23834. const method = object[ name ];
  23835. if ( typeof method === 'function' ) {
  23836. return method( ...params );
  23837. }
  23838. }
  23839. /**
  23840. * Asynchronously calls a function from the script.
  23841. *
  23842. * @param {String} name - The function name.
  23843. * @param {...Any} params - A list of parameters.
  23844. * @return {Promise<Any>} The result of the function call.
  23845. */
  23846. async callAsync( name, ...params ) {
  23847. const object = this.getObject();
  23848. const method = object[ name ];
  23849. if ( typeof method === 'function' ) {
  23850. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23851. }
  23852. }
  23853. /**
  23854. * Overwritten since the node types is inferred from the script's output.
  23855. *
  23856. * @param {NodeBuilder} builder - The current node builder
  23857. * @return {String} The node type.
  23858. */
  23859. getNodeType( builder ) {
  23860. return this.getDefaultOutputNode().getNodeType( builder );
  23861. }
  23862. /**
  23863. * Refreshes the script node.
  23864. *
  23865. * @param {String?} [output=null] - An optional output.
  23866. */
  23867. refresh( output = null ) {
  23868. if ( output !== null ) {
  23869. this.getOutput( output ).refresh();
  23870. } else {
  23871. this._refresh();
  23872. }
  23873. }
  23874. /**
  23875. * Returns an object representation of the script.
  23876. *
  23877. * @return {Object} The result object.
  23878. */
  23879. getObject() {
  23880. if ( this.needsUpdate ) this.dispose();
  23881. if ( this._object !== null ) return this._object;
  23882. //
  23883. const refresh = () => this.refresh();
  23884. const setOutput = ( id, value ) => this.setOutput( id, value );
  23885. const parameters = new Parameters( this );
  23886. const THREE = ScriptableNodeResources.get( 'THREE' );
  23887. const TSL = ScriptableNodeResources.get( 'TSL' );
  23888. const method = this.getMethod();
  23889. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23890. this._object = method( ...params );
  23891. const layout = this._object.layout;
  23892. if ( layout ) {
  23893. if ( layout.cache === false ) {
  23894. this._local.clear();
  23895. }
  23896. // default output
  23897. this._output.outputType = layout.outputType || null;
  23898. if ( Array.isArray( layout.elements ) ) {
  23899. for ( const element of layout.elements ) {
  23900. const id = element.id || element.name;
  23901. if ( element.inputType ) {
  23902. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23903. this.getParameter( id ).inputType = element.inputType;
  23904. }
  23905. if ( element.outputType ) {
  23906. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23907. this.getOutput( id ).outputType = element.outputType;
  23908. }
  23909. }
  23910. }
  23911. }
  23912. return this._object;
  23913. }
  23914. deserialize( data ) {
  23915. super.deserialize( data );
  23916. for ( const name in this.parameters ) {
  23917. let valueNode = this.parameters[ name ];
  23918. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23919. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23920. }
  23921. }
  23922. /**
  23923. * Returns the layout of the script.
  23924. *
  23925. * @return {Object} The script's layout.
  23926. */
  23927. getLayout() {
  23928. return this.getObject().layout;
  23929. }
  23930. /**
  23931. * Returns default node output of the script.
  23932. *
  23933. * @return {Node} The default node output.
  23934. */
  23935. getDefaultOutputNode() {
  23936. const output = this.getDefaultOutput().value;
  23937. if ( output && output.isNode ) {
  23938. return output;
  23939. }
  23940. return float();
  23941. }
  23942. /**
  23943. * Returns default output of the script.
  23944. *
  23945. * @return {ScriptableValueNode} The default output.
  23946. */
  23947. getDefaultOutput() {
  23948. return this._exec()._output;
  23949. }
  23950. /**
  23951. * Returns a function created from the node's script.
  23952. *
  23953. * @return {Function} The function representing the node's code.
  23954. */
  23955. getMethod() {
  23956. if ( this.needsUpdate ) this.dispose();
  23957. if ( this._method !== null ) return this._method;
  23958. //
  23959. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23960. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23961. const properties = interfaceProps.join( ', ' );
  23962. const declarations = 'var ' + properties + '; var output = {};\n';
  23963. const returns = '\nreturn { ...output, ' + properties + ' };';
  23964. const code = declarations + this.codeNode.code + returns;
  23965. //
  23966. this._method = new Function( ...parametersProps, code );
  23967. return this._method;
  23968. }
  23969. /**
  23970. * Frees all internal resources.
  23971. */
  23972. dispose() {
  23973. if ( this._method === null ) return;
  23974. if ( this._object && typeof this._object.dispose === 'function' ) {
  23975. this._object.dispose();
  23976. }
  23977. this._method = null;
  23978. this._object = null;
  23979. this._source = null;
  23980. this._value = null;
  23981. this._needsOutputUpdate = true;
  23982. this._output.value = null;
  23983. this._outputs = {};
  23984. }
  23985. setup() {
  23986. return this.getDefaultOutputNode();
  23987. }
  23988. getCacheKey( force ) {
  23989. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23990. for ( const param in this.parameters ) {
  23991. values.push( this.parameters[ param ].getCacheKey( force ) );
  23992. }
  23993. return hashArray( values );
  23994. }
  23995. set needsUpdate( value ) {
  23996. if ( value === true ) this.dispose();
  23997. }
  23998. get needsUpdate() {
  23999. return this.source !== this._source;
  24000. }
  24001. /**
  24002. * Executes the `main` function of the script.
  24003. *
  24004. * @private
  24005. * @return {ScriptableNode} A reference to this node.
  24006. */
  24007. _exec() {
  24008. if ( this.codeNode === null ) return this;
  24009. if ( this._needsOutputUpdate === true ) {
  24010. this._value = this.call( 'main' );
  24011. this._needsOutputUpdate = false;
  24012. }
  24013. this._output.value = this._value;
  24014. return this;
  24015. }
  24016. /**
  24017. * Executes the refresh.
  24018. *
  24019. * @private
  24020. */
  24021. _refresh() {
  24022. this.needsUpdate = true;
  24023. this._exec();
  24024. this._output.refresh();
  24025. }
  24026. }
  24027. /**
  24028. * TSL function for creating a scriptable node.
  24029. *
  24030. * @function
  24031. * @param {CodeNode?} [codeNode=null] - The code node.
  24032. * @param {Object} [parameters={}] - The parameters definition.
  24033. * @returns {ScriptableNode}
  24034. */
  24035. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  24036. /** @module Fog **/
  24037. /**
  24038. * Returns a node that represents the `z` coordinate in view space
  24039. * for the current fragment. It's a different representation of the
  24040. * default depth value.
  24041. *
  24042. * This value can be part of a computation that defines how the fog
  24043. * density increases when moving away from the camera.
  24044. *
  24045. * @param {NodeBuilder} builder - The current node builder.
  24046. * @return {Node} The viewZ node.
  24047. */
  24048. function getViewZNode( builder ) {
  24049. let viewZ;
  24050. const getViewZ = builder.context.getViewZ;
  24051. if ( getViewZ !== undefined ) {
  24052. viewZ = getViewZ( this );
  24053. }
  24054. return ( viewZ || positionView.z ).negate();
  24055. }
  24056. /**
  24057. * Constructs a new range factor node.
  24058. *
  24059. * @function
  24060. * @param {Node} near - Defines the near value.
  24061. * @param {Node} far - Defines the far value.
  24062. */
  24063. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  24064. const viewZ = getViewZNode( builder );
  24065. return smoothstep( near, far, viewZ );
  24066. } );
  24067. /**
  24068. * Represents an exponential squared fog. This type of fog gives
  24069. * a clear view near the camera and a faster than exponentially
  24070. * densening fog farther from the camera.
  24071. *
  24072. * @function
  24073. * @param {Node} density - Defines the fog density.
  24074. */
  24075. const densityFogFactor = Fn( ( [ density ], builder ) => {
  24076. const viewZ = getViewZNode( builder );
  24077. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  24078. } );
  24079. /**
  24080. * This class can be used to configure a fog for the scene.
  24081. * Nodes of this type are assigned to `Scene.fogNode`.
  24082. *
  24083. * @function
  24084. * @param {Node} color - Defines the color of the fog.
  24085. * @param {Node} factor - Defines how the fog is factored in the scene.
  24086. */
  24087. const fog = Fn( ( [ color, factor ] ) => {
  24088. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  24089. } );
  24090. // Deprecated
  24091. /**
  24092. * @function
  24093. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  24094. *
  24095. * @param {Node} color
  24096. * @param {Node} near
  24097. * @param {Node} far
  24098. * @returns {Function}
  24099. */
  24100. function rangeFog( color, near, far ) { // @deprecated, r171
  24101. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  24102. return fog( color, rangeFogFactor( near, far ) );
  24103. }
  24104. /**
  24105. * @function
  24106. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  24107. *
  24108. * @param {Node} color
  24109. * @param {Node} density
  24110. * @returns {Function}
  24111. */
  24112. function densityFog( color, density ) { // @deprecated, r171
  24113. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  24114. return fog( color, densityFogFactor( density ) );
  24115. }
  24116. /** @module RangeNode **/
  24117. let min = null;
  24118. let max = null;
  24119. /**
  24120. * `RangeNode` generates random instanced attribute data in a defined range.
  24121. * An exemplary use case for this utility node is to generate random per-instance
  24122. * colors:
  24123. * ```js
  24124. * const material = new MeshBasicNodeMaterial();
  24125. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  24126. * const mesh = new InstancedMesh( geometry, material, count );
  24127. * ```
  24128. * @augments Node
  24129. */
  24130. class RangeNode extends Node {
  24131. static get type() {
  24132. return 'RangeNode';
  24133. }
  24134. /**
  24135. * Constructs a new range node.
  24136. *
  24137. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  24138. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  24139. */
  24140. constructor( minNode = float(), maxNode = float() ) {
  24141. super();
  24142. /**
  24143. * A node defining the lower bound of the range.
  24144. *
  24145. * @type {Node<any>}
  24146. * @default float()
  24147. */
  24148. this.minNode = minNode;
  24149. /**
  24150. * A node defining the upper bound of the range.
  24151. *
  24152. * @type {Node<any>}
  24153. * @default float()
  24154. */
  24155. this.maxNode = maxNode;
  24156. }
  24157. /**
  24158. * Returns the vector length which is computed based on the range definition.
  24159. *
  24160. * @param {NodeBuilder} builder - The current node builder.
  24161. * @return {Number} The vector length.
  24162. */
  24163. getVectorLength( builder ) {
  24164. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  24165. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  24166. return minLength > maxLength ? minLength : maxLength;
  24167. }
  24168. /**
  24169. * This method is overwritten since the node type is inferred from range definition.
  24170. *
  24171. * @param {NodeBuilder} builder - The current node builder.
  24172. * @return {String} The node type.
  24173. */
  24174. getNodeType( builder ) {
  24175. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  24176. }
  24177. setup( builder ) {
  24178. const object = builder.object;
  24179. let output = null;
  24180. if ( object.count > 1 ) {
  24181. const minValue = this.minNode.value;
  24182. const maxValue = this.maxNode.value;
  24183. const minLength = builder.getTypeLength( getValueType( minValue ) );
  24184. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  24185. min = min || new Vector4();
  24186. max = max || new Vector4();
  24187. min.setScalar( 0 );
  24188. max.setScalar( 0 );
  24189. if ( minLength === 1 ) min.setScalar( minValue );
  24190. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  24191. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  24192. if ( maxLength === 1 ) max.setScalar( maxValue );
  24193. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  24194. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  24195. const stride = 4;
  24196. const length = stride * object.count;
  24197. const array = new Float32Array( length );
  24198. for ( let i = 0; i < length; i ++ ) {
  24199. const index = i % stride;
  24200. const minElementValue = min.getComponent( index );
  24201. const maxElementValue = max.getComponent( index );
  24202. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  24203. }
  24204. const nodeType = this.getNodeType( builder );
  24205. if ( object.count <= 4096 ) {
  24206. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  24207. } else {
  24208. // TODO: Improve anonymous buffer attribute creation removing this part
  24209. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  24210. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  24211. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  24212. }
  24213. } else {
  24214. output = float( 0 );
  24215. }
  24216. return output;
  24217. }
  24218. }
  24219. /**
  24220. * TSL function for creating a range node.
  24221. *
  24222. * @function
  24223. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  24224. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  24225. * @returns {RangeNode}
  24226. */
  24227. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  24228. /** @module ComputeBuiltinNode **/
  24229. /**
  24230. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  24231. * about the currently running dispatch and/or the device it is running on.
  24232. *
  24233. * This node can only be used with a WebGPU backend.
  24234. *
  24235. * @augments Node
  24236. */
  24237. class ComputeBuiltinNode extends Node {
  24238. static get type() {
  24239. return 'ComputeBuiltinNode';
  24240. }
  24241. /**
  24242. * Constructs a new compute builtin node.
  24243. *
  24244. * @param {String} builtinName - The built-in name.
  24245. * @param {String} nodeType - The node type.
  24246. */
  24247. constructor( builtinName, nodeType ) {
  24248. super( nodeType );
  24249. /**
  24250. * The built-in name.
  24251. *
  24252. * @private
  24253. * @type {String}
  24254. */
  24255. this._builtinName = builtinName;
  24256. }
  24257. /**
  24258. * This method is overwritten since hash is derived from the built-in name.
  24259. *
  24260. * @param {NodeBuilder} builder - The current node builder.
  24261. * @return {String} The hash.
  24262. */
  24263. getHash( builder ) {
  24264. return this.getBuiltinName( builder );
  24265. }
  24266. /**
  24267. * This method is overwritten since the node type is simply derived from `nodeType`..
  24268. *
  24269. * @param {NodeBuilder} builder - The current node builder.
  24270. * @return {String} The node type.
  24271. */
  24272. getNodeType( /*builder*/ ) {
  24273. return this.nodeType;
  24274. }
  24275. /**
  24276. * Sets the builtin name.
  24277. *
  24278. * @param {String} builtinName - The built-in name.
  24279. * @return {ComputeBuiltinNode} A reference to this node.
  24280. */
  24281. setBuiltinName( builtinName ) {
  24282. this._builtinName = builtinName;
  24283. return this;
  24284. }
  24285. /**
  24286. * Returns the builtin name.
  24287. *
  24288. * @param {NodeBuilder} builder - The current node builder.
  24289. * @return {String} The builtin name.
  24290. */
  24291. getBuiltinName( /*builder*/ ) {
  24292. return this._builtinName;
  24293. }
  24294. /**
  24295. * Whether the current node builder has the builtin or not.
  24296. *
  24297. * @param {NodeBuilder} builder - The current node builder.
  24298. */
  24299. hasBuiltin( builder ) {
  24300. builder.hasBuiltin( this._builtinName );
  24301. }
  24302. generate( builder, output ) {
  24303. const builtinName = this.getBuiltinName( builder );
  24304. const nodeType = this.getNodeType( builder );
  24305. if ( builder.shaderStage === 'compute' ) {
  24306. return builder.format( builtinName, nodeType, output );
  24307. } else {
  24308. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  24309. return builder.generateConst( nodeType );
  24310. }
  24311. }
  24312. serialize( data ) {
  24313. super.serialize( data );
  24314. data.global = this.global;
  24315. data._builtinName = this._builtinName;
  24316. }
  24317. deserialize( data ) {
  24318. super.deserialize( data );
  24319. this.global = data.global;
  24320. this._builtinName = data._builtinName;
  24321. }
  24322. }
  24323. /**
  24324. * TSL function for creating a compute builtin node.
  24325. *
  24326. * @function
  24327. * @param {String} name - The built-in name.
  24328. * @param {String} nodeType - The node type.
  24329. * @returns {ComputeBuiltinNode}
  24330. */
  24331. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  24332. /**
  24333. * TSL function for creating a `numWorkgroups` builtin node.
  24334. * Represents the number of workgroups dispatched by the compute shader.
  24335. * ```js
  24336. * // Run 512 invocations/threads with a workgroup size of 128.
  24337. * const computeFn = Fn(() => {
  24338. *
  24339. * // numWorkgroups.x = 4
  24340. * storageBuffer.element(0).assign(numWorkgroups.x)
  24341. *
  24342. * })().compute(512, [128]);
  24343. *
  24344. * // Run 512 invocations/threads with the default workgroup size of 64.
  24345. * const computeFn = Fn(() => {
  24346. *
  24347. * // numWorkgroups.x = 8
  24348. * storageBuffer.element(0).assign(numWorkgroups.x)
  24349. *
  24350. * })().compute(512);
  24351. * ```
  24352. *
  24353. * @function
  24354. * @returns {ComputeBuiltinNode<uvec3>}
  24355. */
  24356. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  24357. /**
  24358. * TSL function for creating a `workgroupId` builtin node.
  24359. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  24360. * ```js
  24361. * // Execute 12 compute threads with a workgroup size of 3.
  24362. * const computeFn = Fn( () => {
  24363. *
  24364. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  24365. *
  24366. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  24367. *
  24368. * } ).Else( () => {
  24369. *
  24370. * storageBuffer.element( instanceIndex ).assign( 0 );
  24371. *
  24372. * } );
  24373. *
  24374. * } )().compute( 12, [ 3 ] );
  24375. *
  24376. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  24377. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  24378. * ```
  24379. *
  24380. * @function
  24381. * @returns {ComputeBuiltinNode<uvec3>}
  24382. */
  24383. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  24384. /**
  24385. * TSL function for creating a `globalId` builtin node. A non-linearized 3-dimensional
  24386. * representation of the current invocation's position within a 3D global grid.
  24387. *
  24388. * @function
  24389. * @returns {ComputeBuiltinNode<uvec3>}
  24390. */
  24391. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  24392. /**
  24393. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  24394. * representation of the current invocation's position within a 3D workgroup grid.
  24395. *
  24396. * @function
  24397. * @returns {ComputeBuiltinNode<uvec3>}
  24398. */
  24399. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  24400. /**
  24401. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  24402. * that exposes the size of the current invocation's subgroup.
  24403. *
  24404. * @function
  24405. * @returns {ComputeBuiltinNode<uint>}
  24406. */
  24407. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  24408. /** @module BarrierNode **/
  24409. /**
  24410. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  24411. *
  24412. * This node can only be used with a WebGPU backend.
  24413. *
  24414. * @augments Node
  24415. */
  24416. class BarrierNode extends Node {
  24417. /**
  24418. * Constructs a new barrier node.
  24419. *
  24420. * @param {String} scope - The scope defines the behavior of the node.
  24421. */
  24422. constructor( scope ) {
  24423. super();
  24424. this.scope = scope;
  24425. }
  24426. generate( builder ) {
  24427. const { scope } = this;
  24428. const { renderer } = builder;
  24429. if ( renderer.backend.isWebGLBackend === true ) {
  24430. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  24431. } else {
  24432. builder.addLineFlowCode( `${scope}Barrier()`, this );
  24433. }
  24434. }
  24435. }
  24436. /**
  24437. * TSL function for creating a barrier node.
  24438. *
  24439. * @function
  24440. * @param {String} scope - The scope defines the behavior of the node..
  24441. * @returns {BarrierNode}
  24442. */
  24443. const barrier = nodeProxy( BarrierNode );
  24444. /**
  24445. * TSL function for creating a workgroup barrier. All compute shader
  24446. * invocations must wait for each invocation within a workgroup to
  24447. * complete before the barrier can be surpassed.
  24448. *
  24449. * @function
  24450. * @returns {BarrierNode}
  24451. */
  24452. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  24453. /**
  24454. * TSL function for creating a storage barrier. All invocations must
  24455. * wait for each access to variables within the 'storage' address space
  24456. * to complete before the barrier can be passed.
  24457. *
  24458. * @function
  24459. * @returns {BarrierNode}
  24460. */
  24461. const storageBarrier = () => barrier( 'storage' ).append();
  24462. /**
  24463. * TSL function for creating a texture barrier. All invocations must
  24464. * wait for each access to variables within the 'texture' address space
  24465. * to complete before the barrier can be passed.
  24466. *
  24467. * @function
  24468. * @returns {BarrierNode}
  24469. */
  24470. const textureBarrier = () => barrier( 'texture' ).append();
  24471. /** @module WorkgroupInfoNode **/
  24472. /**
  24473. * Represents an element of a 'workgroup' scoped buffer.
  24474. *
  24475. * @augments ArrayElementNode
  24476. */
  24477. class WorkgroupInfoElementNode extends ArrayElementNode {
  24478. /**
  24479. * Constructs a new workgroup info element node.
  24480. *
  24481. * @param {Node} workgroupInfoNode - The workgroup info node.
  24482. * @param {Node} indexNode - The index node that defines the element access.
  24483. */
  24484. constructor( workgroupInfoNode, indexNode ) {
  24485. super( workgroupInfoNode, indexNode );
  24486. /**
  24487. * This flag can be used for type testing.
  24488. *
  24489. * @type {Boolean}
  24490. * @readonly
  24491. * @default true
  24492. */
  24493. this.isWorkgroupInfoElementNode = true;
  24494. }
  24495. generate( builder, output ) {
  24496. let snippet;
  24497. const isAssignContext = builder.context.assign;
  24498. snippet = super.generate( builder );
  24499. if ( isAssignContext !== true ) {
  24500. const type = this.getNodeType( builder );
  24501. snippet = builder.format( snippet, type, output );
  24502. }
  24503. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  24504. return snippet;
  24505. }
  24506. }
  24507. /**
  24508. * A node allowing the user to create a 'workgroup' scoped buffer within the
  24509. * context of a compute shader. Typically, workgroup scoped buffers are
  24510. * created to hold data that is transferred from a global storage scope into
  24511. * a local workgroup scope. For invocations within a workgroup, data
  24512. * access speeds on 'workgroup' scoped buffers can be significantly faster
  24513. * than similar access operations on globally accessible storage buffers.
  24514. *
  24515. * This node can only be used with a WebGPU backend.
  24516. *
  24517. * @augments Node
  24518. */
  24519. class WorkgroupInfoNode extends Node {
  24520. /**
  24521. * Constructs a new buffer scoped to type scope.
  24522. *
  24523. * @param {String} scope - TODO.
  24524. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  24525. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  24526. */
  24527. constructor( scope, bufferType, bufferCount = 0 ) {
  24528. super( bufferType );
  24529. /**
  24530. * The buffer type.
  24531. *
  24532. * @type {String}
  24533. */
  24534. this.bufferType = bufferType;
  24535. /**
  24536. * The buffer count.
  24537. *
  24538. * @type {Number}
  24539. * @default 0
  24540. */
  24541. this.bufferCount = bufferCount;
  24542. /**
  24543. * This flag can be used for type testing.
  24544. *
  24545. * @type {Boolean}
  24546. * @readonly
  24547. * @default true
  24548. */
  24549. this.isWorkgroupInfoNode = true;
  24550. /**
  24551. * The data type of the array buffer.
  24552. *
  24553. * @type {String}
  24554. */
  24555. this.elementType = bufferType;
  24556. /**
  24557. * TODO.
  24558. *
  24559. * @type {String}
  24560. */
  24561. this.scope = scope;
  24562. }
  24563. /**
  24564. * Sets the name/label of this node.
  24565. *
  24566. * @param {String} name - The name to set.
  24567. * @return {WorkgroupInfoNode} A reference to this node.
  24568. */
  24569. label( name ) {
  24570. this.name = name;
  24571. return this;
  24572. }
  24573. /**
  24574. * Sets the scope of this node.
  24575. *
  24576. * @param {String} scope - The scope to set.
  24577. * @return {WorkgroupInfoNode} A reference to this node.
  24578. */
  24579. setScope( scope ) {
  24580. this.scope = scope;
  24581. return this;
  24582. }
  24583. /**
  24584. * The data type of the array buffer.
  24585. *
  24586. * @return {String} The element type.
  24587. */
  24588. getElementType() {
  24589. return this.elementType;
  24590. }
  24591. /**
  24592. * Overwrites the default implementation since the input type
  24593. * is inferred from the scope.
  24594. *
  24595. * @param {NodeBuilder} builder - The current node builder.
  24596. * @return {String} The input type.
  24597. */
  24598. getInputType( /*builder*/ ) {
  24599. return `${this.scope}Array`;
  24600. }
  24601. /**
  24602. * This method can be used to access elements via an index node.
  24603. *
  24604. * @param {IndexNode} indexNode - indexNode.
  24605. * @return {WorkgroupInfoElementNode} A reference to an element.
  24606. */
  24607. element( indexNode ) {
  24608. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  24609. }
  24610. generate( builder ) {
  24611. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  24612. }
  24613. }
  24614. /**
  24615. * TSL function for creating a workgroup info node.
  24616. * Creates a new 'workgroup' scoped array buffer.
  24617. *
  24618. * @function
  24619. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  24620. * @param {Number} [count=0] - The number of elements in the buffer.
  24621. * @returns {WorkgroupInfoNode}
  24622. */
  24623. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  24624. /** @module AtomicFunctionNode **/
  24625. /**
  24626. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  24627. * within a shader. In an atomic function, any modification to an atomic variable will
  24628. * occur as an indivisible step with a defined order relative to other modifications.
  24629. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  24630. * atomic operations will not interfere with each other.
  24631. *
  24632. * This node can only be used with a WebGPU backend.
  24633. *
  24634. * @augments TempNode
  24635. */
  24636. class AtomicFunctionNode extends TempNode {
  24637. static get type() {
  24638. return 'AtomicFunctionNode';
  24639. }
  24640. /**
  24641. * Constructs a new atomic function node.
  24642. *
  24643. * @param {String} method - The signature of the atomic function to construct.
  24644. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24645. * @param {Node} valueNode - The value that mutates the atomic variable.
  24646. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24647. */
  24648. constructor( method, pointerNode, valueNode, storeNode = null ) {
  24649. super( 'uint' );
  24650. /**
  24651. * The signature of the atomic function to construct.
  24652. *
  24653. * @type {String}
  24654. */
  24655. this.method = method;
  24656. /**
  24657. * An atomic variable or element of an atomic buffer.
  24658. *
  24659. * @type {Node}
  24660. */
  24661. this.pointerNode = pointerNode;
  24662. /**
  24663. * A value that modifies the atomic variable.
  24664. *
  24665. * @type {Node}
  24666. */
  24667. this.valueNode = valueNode;
  24668. /**
  24669. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24670. *
  24671. * @type {Node?}
  24672. * @default null
  24673. */
  24674. this.storeNode = storeNode;
  24675. }
  24676. /**
  24677. * Overwrites the default implementation to return the type of
  24678. * the pointer node.
  24679. *
  24680. * @param {NodeBuilder} builder - The current node builder.
  24681. * @return {String} The input type.
  24682. */
  24683. getInputType( builder ) {
  24684. return this.pointerNode.getNodeType( builder );
  24685. }
  24686. /**
  24687. * Overwritten since the node type is inferred from the input type.
  24688. *
  24689. * @param {NodeBuilder} builder - The current node builder.
  24690. * @return {String} The node type.
  24691. */
  24692. getNodeType( builder ) {
  24693. return this.getInputType( builder );
  24694. }
  24695. generate( builder ) {
  24696. const method = this.method;
  24697. const type = this.getNodeType( builder );
  24698. const inputType = this.getInputType( builder );
  24699. const a = this.pointerNode;
  24700. const b = this.valueNode;
  24701. const params = [];
  24702. params.push( `&${ a.build( builder, inputType ) }` );
  24703. if ( b !== null ) {
  24704. params.push( b.build( builder, inputType ) );
  24705. }
  24706. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  24707. if ( this.storeNode !== null ) {
  24708. const varSnippet = this.storeNode.build( builder, inputType );
  24709. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24710. } else {
  24711. builder.addLineFlowCode( methodSnippet, this );
  24712. }
  24713. }
  24714. }
  24715. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24716. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24717. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24718. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24719. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24720. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24721. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24722. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24723. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24724. /**
  24725. * TSL function for creating an atomic function node.
  24726. *
  24727. * @function
  24728. * @param {String} method - The signature of the atomic function to construct.
  24729. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24730. * @param {Node} valueNode - The value that mutates the atomic variable.
  24731. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24732. * @returns {AtomicFunctionNode}
  24733. */
  24734. const atomicNode = nodeProxy( AtomicFunctionNode );
  24735. /**
  24736. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  24737. *
  24738. * @function
  24739. * @param {String} method - The signature of the atomic function to construct.
  24740. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24741. * @param {Node} valueNode - The value that mutates the atomic variable.
  24742. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24743. * @returns {AtomicFunctionNode}
  24744. */
  24745. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24746. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24747. node.append();
  24748. return node;
  24749. };
  24750. /**
  24751. * Loads the value stored in the atomic variable.
  24752. *
  24753. * @function
  24754. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24755. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24756. * @returns {AtomicFunctionNode}
  24757. */
  24758. const atomicLoad = ( pointerNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null, storeNode );
  24759. /**
  24760. * Stores a value in the atomic variable.
  24761. *
  24762. * @function
  24763. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24764. * @param {Node} valueNode - The value that mutates the atomic variable.
  24765. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24766. * @returns {AtomicFunctionNode}
  24767. */
  24768. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24769. /**
  24770. * Increments the value stored in the atomic variable.
  24771. *
  24772. * @function
  24773. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24774. * @param {Node} valueNode - The value that mutates the atomic variable.
  24775. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24776. * @returns {AtomicFunctionNode}
  24777. */
  24778. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24779. /**
  24780. * Decrements the value stored in the atomic variable.
  24781. *
  24782. * @function
  24783. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24784. * @param {Node} valueNode - The value that mutates the atomic variable.
  24785. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24786. * @returns {AtomicFunctionNode}
  24787. */
  24788. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24789. /**
  24790. * Stores in an atomic variable the maximum between its current value and a parameter.
  24791. *
  24792. * @function
  24793. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24794. * @param {Node} valueNode - The value that mutates the atomic variable.
  24795. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24796. * @returns {AtomicFunctionNode}
  24797. */
  24798. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24799. /**
  24800. * Stores in an atomic variable the minimum between its current value and a parameter.
  24801. *
  24802. * @function
  24803. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24804. * @param {Node} valueNode - The value that mutates the atomic variable.
  24805. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24806. * @returns {AtomicFunctionNode}
  24807. */
  24808. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24809. /**
  24810. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24811. *
  24812. * @function
  24813. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24814. * @param {Node} valueNode - The value that mutates the atomic variable.
  24815. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24816. * @returns {AtomicFunctionNode}
  24817. */
  24818. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24819. /**
  24820. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24821. *
  24822. * @function
  24823. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24824. * @param {Node} valueNode - The value that mutates the atomic variable.
  24825. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24826. * @returns {AtomicFunctionNode}
  24827. */
  24828. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24829. /**
  24830. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24831. *
  24832. * @function
  24833. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24834. * @param {Node} valueNode - The value that mutates the atomic variable.
  24835. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24836. * @returns {AtomicFunctionNode}
  24837. */
  24838. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24839. /** @module Lights **/
  24840. let uniformsLib;
  24841. function getLightData( light ) {
  24842. uniformsLib = uniformsLib || new WeakMap();
  24843. let uniforms = uniformsLib.get( light );
  24844. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24845. return uniforms;
  24846. }
  24847. /**
  24848. * TSL function for getting a shadow matrix uniform node for the given light.
  24849. *
  24850. * @function
  24851. * @param {Light} light -The light source.
  24852. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24853. */
  24854. function lightShadowMatrix( light ) {
  24855. const data = getLightData( light );
  24856. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24857. if ( light.castShadow !== true ) {
  24858. light.shadow.updateMatrices( light );
  24859. }
  24860. return light.shadow.matrix;
  24861. } ) );
  24862. }
  24863. /**
  24864. * TSL function for getting projected uv coordinates for the given light.
  24865. * Relevant when using maps with spot lights.
  24866. *
  24867. * @function
  24868. * @param {Light} light -The light source.
  24869. * @returns {Node<vec3>} The projected uvs.
  24870. */
  24871. function lightProjectionUV( light ) {
  24872. const data = getLightData( light );
  24873. if ( data.projectionUV === undefined ) {
  24874. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24875. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24876. }
  24877. return data.projectionUV;
  24878. }
  24879. /**
  24880. * TSL function for getting the position in world space for the given light.
  24881. *
  24882. * @function
  24883. * @param {Light} light -The light source.
  24884. * @returns {UniformNode<vec3>} The light's position in world space.
  24885. */
  24886. function lightPosition( light ) {
  24887. const data = getLightData( light );
  24888. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24889. }
  24890. /**
  24891. * TSL function for getting the light target position in world space for the given light.
  24892. *
  24893. * @function
  24894. * @param {Light} light -The light source.
  24895. * @returns {UniformNode<vec3>} The light target position in world space.
  24896. */
  24897. function lightTargetPosition( light ) {
  24898. const data = getLightData( light );
  24899. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24900. }
  24901. /**
  24902. * TSL function for getting the position in view space for the given light.
  24903. *
  24904. * @function
  24905. * @param {Light} light -The light source.
  24906. * @returns {UniformNode<vec3>} The light's position in view space.
  24907. */
  24908. function lightViewPosition( light ) {
  24909. const data = getLightData( light );
  24910. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24911. self.value = self.value || new Vector3();
  24912. self.value.setFromMatrixPosition( light.matrixWorld );
  24913. self.value.applyMatrix4( camera.matrixWorldInverse );
  24914. } ) );
  24915. }
  24916. /**
  24917. * TSL function for getting the light target direction for the given light.
  24918. *
  24919. * @function
  24920. * @param {Light} light -The light source.
  24921. * @returns {Node<vec3>} The light's target direction.
  24922. */
  24923. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24924. /** @module LightsNode **/
  24925. const sortLights = ( lights ) => {
  24926. return lights.sort( ( a, b ) => a.id - b.id );
  24927. };
  24928. const getLightNodeById = ( id, lightNodes ) => {
  24929. for ( const lightNode of lightNodes ) {
  24930. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24931. return lightNode;
  24932. }
  24933. }
  24934. return null;
  24935. };
  24936. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24937. /**
  24938. * This node represents the scene's lighting and manages the lighting model's life cycle
  24939. * for the current build 3D object. It is responsible for computing the total outgoing
  24940. * light in a given lighting context.
  24941. *
  24942. * @augments Node
  24943. */
  24944. class LightsNode extends Node {
  24945. static get type() {
  24946. return 'LightsNode';
  24947. }
  24948. /**
  24949. * Constructs a new lights node.
  24950. */
  24951. constructor() {
  24952. super( 'vec3' );
  24953. /**
  24954. * A node representing the total diffuse light.
  24955. *
  24956. * @type {Node<vec3>}
  24957. */
  24958. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24959. /**
  24960. * A node representing the total specular light.
  24961. *
  24962. * @type {Node<vec3>}
  24963. */
  24964. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24965. /**
  24966. * A node representing the outgoing light.
  24967. *
  24968. * @type {Node<vec3>}
  24969. */
  24970. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24971. /**
  24972. * An array representing the lights in the scene.
  24973. *
  24974. * @private
  24975. * @type {Array<Light>}
  24976. */
  24977. this._lights = [];
  24978. /**
  24979. * For each light in the scene, this node will create a
  24980. * corresponding light node.
  24981. *
  24982. * @private
  24983. * @type {Array<LightingNode>?}
  24984. * @default null
  24985. */
  24986. this._lightNodes = null;
  24987. /**
  24988. * A hash for identifying the current light nodes setup.
  24989. *
  24990. * @private
  24991. * @type {String?}
  24992. * @default null
  24993. */
  24994. this._lightNodesHash = null;
  24995. /**
  24996. * `LightsNode` sets this property to `true` by default.
  24997. *
  24998. * @type {Boolean}
  24999. * @default true
  25000. */
  25001. this.global = true;
  25002. }
  25003. /**
  25004. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25005. * light IDs into the cache key.
  25006. *
  25007. * @return {Number} The custom cache key.
  25008. */
  25009. customCacheKey() {
  25010. const lightIDs = [];
  25011. const lights = this._lights;
  25012. for ( let i = 0; i < lights.length; i ++ ) {
  25013. lightIDs.push( lights[ i ].id );
  25014. }
  25015. return hashArray( lightIDs );
  25016. }
  25017. /**
  25018. * Computes a hash value for identifying the current light nodes setup.
  25019. *
  25020. * @param {NodeBuilder} builder - A reference to the current node builder.
  25021. * @return {String} The computed hash.
  25022. */
  25023. getHash( builder ) {
  25024. if ( this._lightNodesHash === null ) {
  25025. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25026. const hash = [];
  25027. for ( const lightNode of this._lightNodes ) {
  25028. hash.push( lightNode.getSelf().getHash() );
  25029. }
  25030. this._lightNodesHash = 'lights-' + hash.join( ',' );
  25031. }
  25032. return this._lightNodesHash;
  25033. }
  25034. analyze( builder ) {
  25035. const properties = builder.getDataFromNode( this );
  25036. for ( const node of properties.nodes ) {
  25037. node.build( builder );
  25038. }
  25039. }
  25040. /**
  25041. * Creates lighting nodes for each scene light. This makes it possible to further
  25042. * process lights in the node system.
  25043. *
  25044. * @param {NodeBuilder} builder - A reference to the current node builder.
  25045. */
  25046. setupLightsNode( builder ) {
  25047. const lightNodes = [];
  25048. const previousLightNodes = this._lightNodes;
  25049. const lights = sortLights( this._lights );
  25050. const nodeLibrary = builder.renderer.library;
  25051. for ( const light of lights ) {
  25052. if ( light.isNode ) {
  25053. lightNodes.push( nodeObject( light ) );
  25054. } else {
  25055. let lightNode = null;
  25056. if ( previousLightNodes !== null ) {
  25057. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  25058. }
  25059. if ( lightNode === null ) {
  25060. // find the corresponding node type for a given light
  25061. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  25062. if ( lightNodeClass === null ) {
  25063. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  25064. continue;
  25065. }
  25066. let lightNode = null;
  25067. if ( ! _lightsNodeRef.has( light ) ) {
  25068. lightNode = nodeObject( new lightNodeClass( light ) );
  25069. _lightsNodeRef.set( light, lightNode );
  25070. } else {
  25071. lightNode = _lightsNodeRef.get( light );
  25072. }
  25073. lightNodes.push( lightNode );
  25074. }
  25075. }
  25076. }
  25077. this._lightNodes = lightNodes;
  25078. }
  25079. /**
  25080. * Setups the internal lights by building all respective
  25081. * light nodes.
  25082. *
  25083. * @param {NodeBuilder} builder - A reference to the current node builder.
  25084. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  25085. */
  25086. setupLights( builder, lightNodes ) {
  25087. for ( const lightNode of lightNodes ) {
  25088. lightNode.build( builder );
  25089. }
  25090. }
  25091. /**
  25092. * The implementation makes sure that for each light in the scene
  25093. * there is a corresponding light node. By building the light nodes
  25094. * and evaluating the lighting model the outgoing light is computed.
  25095. *
  25096. * @param {NodeBuilder} builder - A reference to the current node builder.
  25097. * @return {Node<vec3>} A node representing the outgoing light.
  25098. */
  25099. setup( builder ) {
  25100. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  25101. const context = builder.context;
  25102. const lightingModel = context.lightingModel;
  25103. let outgoingLightNode = this.outgoingLightNode;
  25104. if ( lightingModel ) {
  25105. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  25106. context.outgoingLight = outgoingLightNode;
  25107. const stack = builder.addStack();
  25108. //
  25109. const properties = builder.getDataFromNode( this );
  25110. properties.nodes = stack.nodes;
  25111. //
  25112. lightingModel.start( context, stack, builder );
  25113. // lights
  25114. this.setupLights( builder, _lightNodes );
  25115. //
  25116. lightingModel.indirect( context, stack, builder );
  25117. //
  25118. const { backdrop, backdropAlpha } = context;
  25119. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  25120. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  25121. if ( backdrop !== null ) {
  25122. if ( backdropAlpha !== null ) {
  25123. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  25124. } else {
  25125. totalDiffuse = vec3( backdrop );
  25126. }
  25127. context.material.transparent = true;
  25128. }
  25129. totalDiffuseNode.assign( totalDiffuse );
  25130. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  25131. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  25132. //
  25133. lightingModel.finish( context, stack, builder );
  25134. //
  25135. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  25136. }
  25137. return outgoingLightNode;
  25138. }
  25139. /**
  25140. * Configures this node with an array of lights.
  25141. *
  25142. * @param {Array<Light>} lights - An array of lights.
  25143. * @return {LightsNode} A reference to this node.
  25144. */
  25145. setLights( lights ) {
  25146. this._lights = lights;
  25147. this._lightNodes = null;
  25148. this._lightNodesHash = null;
  25149. return this;
  25150. }
  25151. /**
  25152. * Returns an array of the scene's lights.
  25153. *
  25154. * @return {Array<Light>} The scene's lights.
  25155. */
  25156. getLights() {
  25157. return this._lights;
  25158. }
  25159. /**
  25160. * Whether the scene has lights or not.
  25161. *
  25162. * @type {Boolean}
  25163. */
  25164. get hasLights() {
  25165. return this._lights.length > 0;
  25166. }
  25167. }
  25168. /**
  25169. * TSL function for creating an instance of `LightsNode` and configuring
  25170. * it with the given array of lights.
  25171. *
  25172. * @function
  25173. * @param {Array<Light>} lights - An array of lights.
  25174. * @return {LightsNode} The created lights node.
  25175. */
  25176. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  25177. /** @module ShadowBaseNode **/
  25178. /**
  25179. * Base class for all shadow nodes.
  25180. *
  25181. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  25182. * Lighting nodes might share the same shadow node type or use specific ones depending on
  25183. * their requirements.
  25184. *
  25185. * @augments Node
  25186. */
  25187. class ShadowBaseNode extends Node {
  25188. static get type() {
  25189. return 'ShadowBaseNode';
  25190. }
  25191. /**
  25192. * Constructs a new shadow base node.
  25193. *
  25194. * @param {Light} light - The shadow casting light.
  25195. */
  25196. constructor( light ) {
  25197. super();
  25198. /**
  25199. * The shadow casting light.
  25200. *
  25201. * @type {Light}
  25202. */
  25203. this.light = light;
  25204. /**
  25205. * Overwritten since shadows are updated by default per render.
  25206. *
  25207. * @type {String}
  25208. * @default 'render'
  25209. */
  25210. this.updateBeforeType = NodeUpdateType.RENDER;
  25211. /**
  25212. * This flag can be used for type testing.
  25213. *
  25214. * @type {Boolean}
  25215. * @readonly
  25216. * @default true
  25217. */
  25218. this.isShadowBaseNode = true;
  25219. }
  25220. /**
  25221. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  25222. *
  25223. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  25224. */
  25225. setupShadowPosition( { material } ) {
  25226. // Use assign inside an Fn()
  25227. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  25228. }
  25229. /**
  25230. * Can be called when the shadow isn't required anymore. That can happen when
  25231. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  25232. * to `false`.
  25233. */
  25234. dispose() {
  25235. this.updateBeforeType = NodeUpdateType.NONE;
  25236. }
  25237. }
  25238. /**
  25239. * TSL object that represents the vertex position in world space during the shadow pass.
  25240. *
  25241. * @type {Node<vec3>}
  25242. */
  25243. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  25244. /** @module RendererUtils **/
  25245. /**
  25246. * Saves the state of the given renderer and stores it into the given state object.
  25247. *
  25248. * If not state object is provided, the function creates one.
  25249. *
  25250. * @function
  25251. * @param {Renderer} renderer - The renderer.
  25252. * @param {Object} [state={}] - The state.
  25253. * @return {Object} The state.
  25254. */
  25255. function saveRendererState( renderer, state = {} ) {
  25256. state.toneMapping = renderer.toneMapping;
  25257. state.toneMappingExposure = renderer.toneMappingExposure;
  25258. state.outputColorSpace = renderer.outputColorSpace;
  25259. state.renderTarget = renderer.getRenderTarget();
  25260. state.activeCubeFace = renderer.getActiveCubeFace();
  25261. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  25262. state.renderObjectFunction = renderer.getRenderObjectFunction();
  25263. state.pixelRatio = renderer.getPixelRatio();
  25264. state.mrt = renderer.getMRT();
  25265. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  25266. state.clearAlpha = renderer.getClearAlpha();
  25267. state.autoClear = renderer.autoClear;
  25268. state.scissorTest = renderer.getScissorTest();
  25269. return state;
  25270. }
  25271. /**
  25272. * Saves the state of the given renderer and stores it into the given state object.
  25273. * Besides, the function also resets the state of the renderer to its default values.
  25274. *
  25275. * If not state object is provided, the function creates one.
  25276. *
  25277. * @function
  25278. * @param {Renderer} renderer - The renderer.
  25279. * @param {Object} [state={}] - The state.
  25280. * @return {Object} The state.
  25281. */
  25282. function resetRendererState( renderer, state ) {
  25283. state = saveRendererState( renderer, state );
  25284. renderer.setMRT( null );
  25285. renderer.setRenderObjectFunction( null );
  25286. renderer.setClearColor( 0x000000, 1 );
  25287. renderer.autoClear = true;
  25288. return state;
  25289. }
  25290. /**
  25291. * Restores the state of the given renderer from the given state object.
  25292. *
  25293. * @function
  25294. * @param {Renderer} renderer - The renderer.
  25295. * @param {Object} state - The state to restore.
  25296. */
  25297. function restoreRendererState( renderer, state ) {
  25298. renderer.toneMapping = state.toneMapping;
  25299. renderer.toneMappingExposure = state.toneMappingExposure;
  25300. renderer.outputColorSpace = state.outputColorSpace;
  25301. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  25302. renderer.setRenderObjectFunction( state.renderObjectFunction );
  25303. renderer.setPixelRatio( state.pixelRatio );
  25304. renderer.setMRT( state.mrt );
  25305. renderer.setClearColor( state.clearColor, state.clearAlpha );
  25306. renderer.autoClear = state.autoClear;
  25307. renderer.setScissorTest( state.scissorTest );
  25308. }
  25309. /**
  25310. * Saves the state of the given scene and stores it into the given state object.
  25311. *
  25312. * If not state object is provided, the function creates one.
  25313. *
  25314. * @function
  25315. * @param {Scene} scene - The scene.
  25316. * @param {Object} [state={}] - The state.
  25317. * @return {Object} The state.
  25318. */
  25319. function saveSceneState( scene, state = {} ) {
  25320. state.background = scene.background;
  25321. state.backgroundNode = scene.backgroundNode;
  25322. state.overrideMaterial = scene.overrideMaterial;
  25323. return state;
  25324. }
  25325. /**
  25326. * Saves the state of the given scene and stores it into the given state object.
  25327. * Besides, the function also resets the state of the scene to its default values.
  25328. *
  25329. * If not state object is provided, the function creates one.
  25330. *
  25331. * @function
  25332. * @param {Scene} scene - The scene.
  25333. * @param {Object} [state={}] - The state.
  25334. * @return {Object} The state.
  25335. */
  25336. function resetSceneState( scene, state ) {
  25337. state = saveSceneState( scene, state );
  25338. scene.background = null;
  25339. scene.backgroundNode = null;
  25340. scene.overrideMaterial = null;
  25341. return state;
  25342. }
  25343. /**
  25344. * Restores the state of the given scene from the given state object.
  25345. *
  25346. * @function
  25347. * @param {Scene} scene - The scene.
  25348. * @param {Object} state - The state to restore.
  25349. */
  25350. function restoreSceneState( scene, state ) {
  25351. scene.background = state.background;
  25352. scene.backgroundNode = state.backgroundNode;
  25353. scene.overrideMaterial = state.overrideMaterial;
  25354. }
  25355. /**
  25356. * Saves the state of the given renderer and scene and stores it into the given state object.
  25357. *
  25358. * If not state object is provided, the function creates one.
  25359. *
  25360. * @function
  25361. * @param {Renderer} renderer - The renderer.
  25362. * @param {Scene} scene - The scene.
  25363. * @param {Object} [state={}] - The state.
  25364. * @return {Object} The state.
  25365. */
  25366. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  25367. state = saveRendererState( renderer, state );
  25368. state = saveSceneState( scene, state );
  25369. return state;
  25370. }
  25371. /**
  25372. * Saves the state of the given renderer and scene and stores it into the given state object.
  25373. * Besides, the function also resets the state of the renderer and scene to its default values.
  25374. *
  25375. * If not state object is provided, the function creates one.
  25376. *
  25377. * @function
  25378. * @param {Renderer} renderer - The renderer.
  25379. * @param {Scene} scene - The scene.
  25380. * @param {Object} [state={}] - The state.
  25381. * @return {Object} The state.
  25382. */
  25383. function resetRendererAndSceneState( renderer, scene, state ) {
  25384. state = resetRendererState( renderer, state );
  25385. state = resetSceneState( scene, state );
  25386. return state;
  25387. }
  25388. /**
  25389. * Restores the state of the given renderer and scene from the given state object.
  25390. *
  25391. * @function
  25392. * @param {Renderer} renderer - The renderer.
  25393. * @param {Scene} scene - The scene.
  25394. * @param {Object} state - The state to restore.
  25395. */
  25396. function restoreRendererAndSceneState( renderer, scene, state ) {
  25397. restoreRendererState( renderer, state );
  25398. restoreSceneState( scene, state );
  25399. }
  25400. var RendererUtils = /*#__PURE__*/Object.freeze({
  25401. __proto__: null,
  25402. resetRendererAndSceneState: resetRendererAndSceneState,
  25403. resetRendererState: resetRendererState,
  25404. resetSceneState: resetSceneState,
  25405. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25406. restoreRendererState: restoreRendererState,
  25407. restoreSceneState: restoreSceneState,
  25408. saveRendererAndSceneState: saveRendererAndSceneState,
  25409. saveRendererState: saveRendererState,
  25410. saveSceneState: saveSceneState
  25411. });
  25412. /** @module ShadowNode **/
  25413. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  25414. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  25415. let dist = positionWorld.sub( position ).length();
  25416. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  25417. dist = dist.saturate(); // clamp to [ 0, 1 ]
  25418. return dist;
  25419. } );
  25420. const linearShadowDistance = ( light ) => {
  25421. const camera = light.shadow.camera;
  25422. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  25423. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  25424. const referencePosition = objectPosition( light );
  25425. return linearDistance( referencePosition, nearDistance, farDistance );
  25426. };
  25427. const getShadowMaterial = ( light ) => {
  25428. let material = shadowMaterialLib.get( light );
  25429. if ( material === undefined ) {
  25430. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  25431. material = new NodeMaterial();
  25432. material.colorNode = vec4( 0, 0, 0, 1 );
  25433. material.depthNode = depthNode;
  25434. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  25435. material.name = 'ShadowMaterial';
  25436. material.fog = false;
  25437. shadowMaterialLib.set( light, material );
  25438. }
  25439. return material;
  25440. };
  25441. /**
  25442. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  25443. * with a binary `[0,1]` result.
  25444. *
  25445. * @method
  25446. * @param {Object} inputs - The input parameter object.
  25447. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25448. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25449. * @return {Node<float>} The filtering result.
  25450. */
  25451. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25452. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  25453. } );
  25454. /**
  25455. * A shadow filtering function performing PCF filtering.
  25456. *
  25457. * @method
  25458. * @param {Object} inputs - The input parameter object.
  25459. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25460. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25461. * @param {LightShadow} inputs.shadow - The light shadow.
  25462. * @return {Node<float>} The filtering result.
  25463. */
  25464. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25465. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25466. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25467. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25468. const texelSize = vec2( 1 ).div( mapSize );
  25469. const dx0 = texelSize.x.negate().mul( radius );
  25470. const dy0 = texelSize.y.negate().mul( radius );
  25471. const dx1 = texelSize.x.mul( radius );
  25472. const dy1 = texelSize.y.mul( radius );
  25473. const dx2 = dx0.div( 2 );
  25474. const dy2 = dy0.div( 2 );
  25475. const dx3 = dx1.div( 2 );
  25476. const dy3 = dy1.div( 2 );
  25477. return add(
  25478. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25479. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25480. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25481. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25482. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25483. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25484. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25485. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25486. depthCompare( shadowCoord.xy, shadowCoord.z ),
  25487. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25488. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25489. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25490. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25491. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25492. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25493. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25494. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25495. ).mul( 1 / 17 );
  25496. } );
  25497. /**
  25498. * A shadow filtering function performing PCF soft filtering.
  25499. *
  25500. * @method
  25501. * @param {Object} inputs - The input parameter object.
  25502. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25503. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25504. * @param {LightShadow} inputs.shadow - The light shadow.
  25505. * @return {Node<float>} The filtering result.
  25506. */
  25507. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25508. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25509. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25510. const texelSize = vec2( 1 ).div( mapSize );
  25511. const dx = texelSize.x;
  25512. const dy = texelSize.y;
  25513. const uv = shadowCoord.xy;
  25514. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  25515. uv.subAssign( f.mul( texelSize ) );
  25516. return add(
  25517. depthCompare( uv, shadowCoord.z ),
  25518. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  25519. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  25520. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  25521. mix(
  25522. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  25523. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  25524. f.x
  25525. ),
  25526. mix(
  25527. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  25528. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  25529. f.x
  25530. ),
  25531. mix(
  25532. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  25533. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  25534. f.y
  25535. ),
  25536. mix(
  25537. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  25538. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  25539. f.y
  25540. ),
  25541. mix(
  25542. mix(
  25543. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  25544. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  25545. f.x
  25546. ),
  25547. mix(
  25548. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  25549. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  25550. f.x
  25551. ),
  25552. f.y
  25553. )
  25554. ).mul( 1 / 9 );
  25555. } );
  25556. /**
  25557. * A shadow filtering function performing VSM filtering.
  25558. *
  25559. * @method
  25560. * @param {Object} inputs - The input parameter object.
  25561. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25562. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25563. * @return {Node<float>} The filtering result.
  25564. */
  25565. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25566. const occlusion = float( 1 ).toVar();
  25567. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  25568. const hardShadow = step( shadowCoord.z, distribution.x );
  25569. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  25570. const distance = shadowCoord.z.sub( distribution.x );
  25571. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  25572. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  25573. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  25574. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  25575. } );
  25576. return occlusion;
  25577. } );
  25578. /**
  25579. * Represents the shader code for the first VSM render pass.
  25580. *
  25581. * @method
  25582. * @param {Object} inputs - The input parameter object.
  25583. * @param {Node<float>} inputs.samples - The number of samples
  25584. * @param {Node<float>} inputs.radius - The radius.
  25585. * @param {Node<float>} inputs.size - The size.
  25586. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  25587. * @return {Node<vec2>} The VSM output.
  25588. */
  25589. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25590. const mean = float( 0 ).toVar();
  25591. const squaredMean = float( 0 ).toVar();
  25592. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25593. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  25594. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25595. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25596. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  25597. mean.addAssign( depth );
  25598. squaredMean.addAssign( depth.mul( depth ) );
  25599. } );
  25600. mean.divAssign( samples );
  25601. squaredMean.divAssign( samples );
  25602. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25603. return vec2( mean, std_dev );
  25604. } );
  25605. /**
  25606. * Represents the shader code for the second VSM render pass.
  25607. *
  25608. * @method
  25609. * @param {Object} inputs - The input parameter object.
  25610. * @param {Node<float>} inputs.samples - The number of samples
  25611. * @param {Node<float>} inputs.radius - The radius.
  25612. * @param {Node<float>} inputs.size - The size.
  25613. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  25614. * @return {Node<vec2>} The VSM output.
  25615. */
  25616. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25617. const mean = float( 0 ).toVar();
  25618. const squaredMean = float( 0 ).toVar();
  25619. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25620. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  25621. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25622. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25623. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  25624. mean.addAssign( distribution.x );
  25625. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  25626. } );
  25627. mean.divAssign( samples );
  25628. squaredMean.divAssign( samples );
  25629. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25630. return vec2( mean, std_dev );
  25631. } );
  25632. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  25633. //
  25634. let _rendererState;
  25635. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  25636. /**
  25637. * Represents the default shadow implementation for lighting nodes.
  25638. *
  25639. * @augments module:ShadowBaseNode~ShadowBaseNode
  25640. */
  25641. class ShadowNode extends ShadowBaseNode {
  25642. static get type() {
  25643. return 'ShadowNode';
  25644. }
  25645. /**
  25646. * Constructs a new shadow node.
  25647. *
  25648. * @param {Light} light - The shadow casting light.
  25649. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  25650. */
  25651. constructor( light, shadow = null ) {
  25652. super( light );
  25653. /**
  25654. * The light shadow which defines the properties light's
  25655. * shadow.
  25656. *
  25657. * @type {LightShadow?}
  25658. * @default null
  25659. */
  25660. this.shadow = shadow || light.shadow;
  25661. /**
  25662. * A reference to the shadow map which is a render target.
  25663. *
  25664. * @type {RenderTarget?}
  25665. * @default null
  25666. */
  25667. this.shadowMap = null;
  25668. /**
  25669. * Only relevant for VSM shadows. Render target for the
  25670. * first VSM render pass.
  25671. *
  25672. * @type {RenderTarget?}
  25673. * @default null
  25674. */
  25675. this.vsmShadowMapVertical = null;
  25676. /**
  25677. * Only relevant for VSM shadows. Render target for the
  25678. * second VSM render pass.
  25679. *
  25680. * @type {RenderTarget?}
  25681. * @default null
  25682. */
  25683. this.vsmShadowMapHorizontal = null;
  25684. /**
  25685. * Only relevant for VSM shadows. Node material which
  25686. * is used to render the first VSM pass.
  25687. *
  25688. * @type {NodeMaterial?}
  25689. * @default null
  25690. */
  25691. this.vsmMaterialVertical = null;
  25692. /**
  25693. * Only relevant for VSM shadows. Node material which
  25694. * is used to render the second VSM pass.
  25695. *
  25696. * @type {NodeMaterial?}
  25697. * @default null
  25698. */
  25699. this.vsmMaterialHorizontal = null;
  25700. /**
  25701. * A reference to the output node which defines the
  25702. * final result of this shadow node.
  25703. *
  25704. * @type {Node?}
  25705. * @private
  25706. * @default null
  25707. */
  25708. this._node = null;
  25709. /**
  25710. * This flag can be used for type testing.
  25711. *
  25712. * @type {Boolean}
  25713. * @readonly
  25714. * @default true
  25715. */
  25716. this.isShadowNode = true;
  25717. }
  25718. /**
  25719. * Setups the shadow filtering.
  25720. *
  25721. * @param {NodeBuilder} builder - A reference to the current node builder.
  25722. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25723. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25724. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25725. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25726. * @param {LightShadow} inputs.shadow - The light shadow.
  25727. * @return {Node<float>} The result node of the shadow filtering.
  25728. */
  25729. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25730. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25731. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25732. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25733. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25734. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25735. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25736. return frustumTest.select( shadowNode, float( 1 ) );
  25737. }
  25738. /**
  25739. * Setups the shadow coordinates.
  25740. *
  25741. * @param {NodeBuilder} builder - A reference to the current node builder.
  25742. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25743. * @return {Node<vec3>} The shadow coordinates.
  25744. */
  25745. setupShadowCoord( builder, shadowPosition ) {
  25746. const { shadow } = this;
  25747. const { renderer } = builder;
  25748. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25749. let shadowCoord = shadowPosition;
  25750. let coordZ;
  25751. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25752. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25753. coordZ = shadowCoord.z;
  25754. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25755. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25756. }
  25757. } else {
  25758. const w = shadowCoord.w;
  25759. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25760. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25761. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25762. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25763. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25764. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25765. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25766. }
  25767. shadowCoord = vec3(
  25768. shadowCoord.x,
  25769. shadowCoord.y.oneMinus(), // follow webgpu standards
  25770. coordZ.add( bias )
  25771. );
  25772. return shadowCoord;
  25773. }
  25774. /**
  25775. * Returns the shadow filtering function for the given shadow type.
  25776. *
  25777. * @param {Number} type - The shadow type.
  25778. * @return {Function} The filtering function.
  25779. */
  25780. getShadowFilterFn( type ) {
  25781. return _shadowFilterLib[ type ];
  25782. }
  25783. /**
  25784. * Setups the shadow output node.
  25785. *
  25786. * @param {NodeBuilder} builder - A reference to the current node builder.
  25787. * @return {Node<vec3>} The shadow output node.
  25788. */
  25789. setupShadow( builder ) {
  25790. const { renderer } = builder;
  25791. const { light, shadow } = this;
  25792. const shadowMapType = renderer.shadowMap.type;
  25793. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25794. depthTexture.compareFunction = LessCompare;
  25795. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25796. shadowMap.depthTexture = depthTexture;
  25797. shadow.camera.updateProjectionMatrix();
  25798. // VSM
  25799. if ( shadowMapType === VSMShadowMap ) {
  25800. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25801. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25802. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25803. const shadowPassVertical = texture( depthTexture );
  25804. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25805. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25806. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25807. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25808. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25809. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25810. material.name = 'VSMVertical';
  25811. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25812. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25813. material.name = 'VSMHorizontal';
  25814. }
  25815. //
  25816. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25817. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25818. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25819. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25820. //
  25821. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25822. if ( filterFn === null ) {
  25823. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25824. }
  25825. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25826. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25827. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25828. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25829. this.shadowMap = shadowMap;
  25830. this.shadow.map = shadowMap;
  25831. return shadowOutput;
  25832. }
  25833. /**
  25834. * The implementation performs the setup of the output node. An output is only
  25835. * produces if shadow mapping is globally enabled in the renderer.
  25836. *
  25837. * @param {NodeBuilder} builder - A reference to the current node builder.
  25838. * @return {ShaderCallNodeInternal} The output node.
  25839. */
  25840. setup( builder ) {
  25841. if ( builder.renderer.shadowMap.enabled === false ) return;
  25842. return Fn( () => {
  25843. let node = this._node;
  25844. this.setupShadowPosition( builder );
  25845. if ( node === null ) {
  25846. this._node = node = this.setupShadow( builder );
  25847. }
  25848. if ( builder.material.shadowNode ) { // @deprecated, r171
  25849. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25850. }
  25851. if ( builder.material.receivedShadowNode ) {
  25852. node = builder.material.receivedShadowNode( node );
  25853. }
  25854. return node;
  25855. } )();
  25856. }
  25857. /**
  25858. * Renders the shadow. The logic of this function could be included
  25859. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25860. * nodes might require a custom shadow map rendering. By having a
  25861. * dedicated method, it's easier to overwrite the default behavior.
  25862. *
  25863. * @param {NodeFrame} frame - A reference to the current node frame.
  25864. */
  25865. renderShadow( frame ) {
  25866. const { shadow, shadowMap, light } = this;
  25867. const { renderer, scene } = frame;
  25868. shadow.updateMatrices( light );
  25869. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25870. renderer.render( scene, shadow.camera );
  25871. }
  25872. /**
  25873. * Updates the shadow.
  25874. *
  25875. * @param {NodeFrame} frame - A reference to the current node frame.
  25876. */
  25877. updateShadow( frame ) {
  25878. const { shadowMap, light, shadow } = this;
  25879. const { renderer, scene, camera } = frame;
  25880. const shadowType = renderer.shadowMap.type;
  25881. const depthVersion = shadowMap.depthTexture.version;
  25882. this._depthVersionCached = depthVersion;
  25883. shadow.camera.layers.mask = camera.layers.mask;
  25884. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25885. const currentMRT = renderer.getMRT();
  25886. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25887. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25888. scene.overrideMaterial = getShadowMaterial( light );
  25889. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25890. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25891. if ( useVelocity ) {
  25892. getDataFromObject( object ).useVelocity = true;
  25893. }
  25894. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25895. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25896. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25897. }
  25898. } );
  25899. renderer.setRenderTarget( shadowMap );
  25900. this.renderShadow( frame );
  25901. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25902. // vsm blur pass
  25903. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25904. this.vsmPass( renderer );
  25905. }
  25906. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25907. }
  25908. /**
  25909. * For VSM additional render passes are required.
  25910. *
  25911. * @param {Renderer} renderer - A reference to the current renderer.
  25912. */
  25913. vsmPass( renderer ) {
  25914. const { shadow } = this;
  25915. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25916. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25917. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25918. _quadMesh.material = this.vsmMaterialVertical;
  25919. _quadMesh.render( renderer );
  25920. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25921. _quadMesh.material = this.vsmMaterialHorizontal;
  25922. _quadMesh.render( renderer );
  25923. }
  25924. /**
  25925. * Frees the internal resources of this shadow node.
  25926. */
  25927. dispose() {
  25928. this.shadowMap.dispose();
  25929. this.shadowMap = null;
  25930. if ( this.vsmShadowMapVertical !== null ) {
  25931. this.vsmShadowMapVertical.dispose();
  25932. this.vsmShadowMapVertical = null;
  25933. this.vsmMaterialVertical.dispose();
  25934. this.vsmMaterialVertical = null;
  25935. }
  25936. if ( this.vsmShadowMapHorizontal !== null ) {
  25937. this.vsmShadowMapHorizontal.dispose();
  25938. this.vsmShadowMapHorizontal = null;
  25939. this.vsmMaterialHorizontal.dispose();
  25940. this.vsmMaterialHorizontal = null;
  25941. }
  25942. super.dispose();
  25943. }
  25944. /**
  25945. * The implementation performs the update of the shadow map if necessary.
  25946. *
  25947. * @param {NodeFrame} frame - A reference to the current node frame.
  25948. */
  25949. updateBefore( frame ) {
  25950. const { shadow } = this;
  25951. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25952. if ( needsUpdate ) {
  25953. this.updateShadow( frame );
  25954. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25955. shadow.needsUpdate = false;
  25956. }
  25957. }
  25958. }
  25959. }
  25960. /**
  25961. * TSL function for creating an instance of `ShadowNode`.
  25962. *
  25963. * @function
  25964. * @param {Light} light - The shadow casting light.
  25965. * @param {LightShadow} shadow - The light shadow.
  25966. * @return {ShadowNode} The created shadow node.
  25967. */
  25968. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25969. /**
  25970. * Base class for analytic light nodes.
  25971. *
  25972. * @augments LightingNode
  25973. */
  25974. class AnalyticLightNode extends LightingNode {
  25975. static get type() {
  25976. return 'AnalyticLightNode';
  25977. }
  25978. /**
  25979. * Constructs a new analytic light node.
  25980. *
  25981. * @param {Light?} [light=null] - The light source.
  25982. */
  25983. constructor( light = null ) {
  25984. super();
  25985. /**
  25986. * The light source.
  25987. *
  25988. * @type {Light?}
  25989. * @default null
  25990. */
  25991. this.light = light;
  25992. /**
  25993. * The light's color value.
  25994. *
  25995. * @type {Color}
  25996. */
  25997. this.color = new Color();
  25998. /**
  25999. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  26000. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  26001. *
  26002. * @type {Node}
  26003. */
  26004. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  26005. /**
  26006. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  26007. * The final color node is represented by a different node when using shadows.
  26008. *
  26009. * @type {Node?}
  26010. * @default null
  26011. */
  26012. this.baseColorNode = null;
  26013. /**
  26014. * Represents the light's shadow.
  26015. *
  26016. * @type {ShadowNode?}
  26017. * @default null
  26018. */
  26019. this.shadowNode = null;
  26020. /**
  26021. * Represents the light's shadow color.
  26022. *
  26023. * @type {Node?}
  26024. * @default null
  26025. */
  26026. this.shadowColorNode = null;
  26027. /**
  26028. * This flag can be used for type testing.
  26029. *
  26030. * @type {Boolean}
  26031. * @readonly
  26032. * @default true
  26033. */
  26034. this.isAnalyticLightNode = true;
  26035. /**
  26036. * Overwritten since analytic light nodes are updated
  26037. * once per frame.
  26038. *
  26039. * @type {String}
  26040. * @default 'frame'
  26041. */
  26042. this.updateType = NodeUpdateType.FRAME;
  26043. }
  26044. /**
  26045. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  26046. * `light.id` and `light.castShadow` into the cache key.
  26047. *
  26048. * @return {Number} The custom cache key.
  26049. */
  26050. customCacheKey() {
  26051. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  26052. }
  26053. getHash() {
  26054. return this.light.uuid;
  26055. }
  26056. /**
  26057. * Setups the shadow node for this light. The method exists so concrete light classes
  26058. * can setup different types of shadow nodes.
  26059. *
  26060. * @return {ShadowNode} The created shadow node.
  26061. */
  26062. setupShadowNode() {
  26063. return shadow( this.light );
  26064. }
  26065. /**
  26066. * Setups the shadow for this light. This method is only executed if the light
  26067. * cast shadows and the current build object receives shadows. It incorporates
  26068. * shadows into the lighting computation.
  26069. *
  26070. * @param {NodeBuilder} builder - The current node builder.
  26071. */
  26072. setupShadow( builder ) {
  26073. const { renderer } = builder;
  26074. if ( renderer.shadowMap.enabled === false ) return;
  26075. let shadowColorNode = this.shadowColorNode;
  26076. if ( shadowColorNode === null ) {
  26077. const customShadowNode = this.light.shadow.shadowNode;
  26078. let shadowNode;
  26079. if ( customShadowNode !== undefined ) {
  26080. shadowNode = nodeObject( customShadowNode );
  26081. } else {
  26082. shadowNode = this.setupShadowNode( builder );
  26083. }
  26084. this.shadowNode = shadowNode;
  26085. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  26086. this.baseColorNode = this.colorNode;
  26087. }
  26088. //
  26089. this.colorNode = shadowColorNode;
  26090. }
  26091. /**
  26092. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  26093. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  26094. * invocate the respective interface methods.
  26095. *
  26096. * @param {NodeBuilder} builder - The current node builder.
  26097. */
  26098. setup( builder ) {
  26099. this.colorNode = this.baseColorNode || this.colorNode;
  26100. if ( this.light.castShadow ) {
  26101. if ( builder.object.receiveShadow ) {
  26102. this.setupShadow( builder );
  26103. }
  26104. } else if ( this.shadowNode !== null ) {
  26105. this.shadowNode.dispose();
  26106. this.shadowNode = null;
  26107. this.shadowColorNode = null;
  26108. }
  26109. }
  26110. /**
  26111. * The update method is used to update light uniforms per frame.
  26112. * Potentially overwritten in concrete light nodes to update light
  26113. * specific uniforms.
  26114. *
  26115. * @param {NodeFrame} frame - A reference to the current node frame.
  26116. */
  26117. update( /*frame*/ ) {
  26118. const { light } = this;
  26119. this.color.copy( light.color ).multiplyScalar( light.intensity );
  26120. }
  26121. }
  26122. /** @module LightUtils **/
  26123. /**
  26124. * Represents a `discard` shader operation in TSL.
  26125. *
  26126. * @method
  26127. * @param {Object} inputs - The input parameter object.
  26128. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  26129. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  26130. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  26131. * @return {Node<float>} The distance falloff.
  26132. */
  26133. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  26134. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  26135. // based upon Frostbite 3 Moving to Physically-based Rendering
  26136. // page 32, equation 26: E[window1]
  26137. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  26138. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  26139. return cutoffDistance.greaterThan( 0 ).select(
  26140. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  26141. distanceFalloff
  26142. );
  26143. } ); // validated
  26144. /** @module PointShadowNode **/
  26145. const _clearColor$2 = /*@__PURE__*/ new Color();
  26146. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  26147. // vector suitable for 2D texture mapping. This code uses the following layout for the
  26148. // 2D texture:
  26149. //
  26150. // xzXZ
  26151. // y Y
  26152. //
  26153. // Y - Positive y direction
  26154. // y - Negative y direction
  26155. // X - Positive x direction
  26156. // x - Negative x direction
  26157. // Z - Positive z direction
  26158. // z - Negative z direction
  26159. //
  26160. // Source and test bed:
  26161. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  26162. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  26163. const v = pos.toVar();
  26164. // Number of texels to avoid at the edge of each square
  26165. const absV = abs( v );
  26166. // Intersect unit cube
  26167. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  26168. absV.mulAssign( scaleToCube );
  26169. // Apply scale to avoid seams
  26170. // two texels less per square (one texel will do for NEAREST)
  26171. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  26172. // Unwrap
  26173. // space: -1 ... 1 range for each square
  26174. //
  26175. // #X## dim := ( 4 , 2 )
  26176. // # # center := ( 1 , 1 )
  26177. const planar = vec2( v.xy ).toVar();
  26178. const almostATexel = texelSizeY.mul( 1.5 );
  26179. const almostOne = almostATexel.oneMinus();
  26180. If( absV.z.greaterThanEqual( almostOne ), () => {
  26181. If( v.z.greaterThan( 0.0 ), () => {
  26182. planar.x.assign( sub( 4.0, v.x ) );
  26183. } );
  26184. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  26185. const signX = sign( v.x );
  26186. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  26187. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  26188. const signY = sign( v.y );
  26189. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  26190. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  26191. } );
  26192. // Transform to UV space
  26193. // scale := 0.5 / dim
  26194. // translate := ( center + 0.5 ) / dim
  26195. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  26196. } ).setLayout( {
  26197. name: 'cubeToUV',
  26198. type: 'vec2',
  26199. inputs: [
  26200. { name: 'pos', type: 'vec3' },
  26201. { name: 'texelSizeY', type: 'float' }
  26202. ]
  26203. } );
  26204. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  26205. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  26206. } );
  26207. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  26208. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  26209. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  26210. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  26211. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  26212. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  26213. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  26214. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  26215. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  26216. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  26217. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  26218. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  26219. .mul( 1.0 / 9.0 );
  26220. } );
  26221. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  26222. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  26223. // the vector from the light to the world-space position of the fragment.
  26224. const lightToPosition = shadowCoord.xyz.toVar();
  26225. const lightToPositionLength = lightToPosition.length();
  26226. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  26227. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  26228. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  26229. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  26230. const result = float( 1.0 ).toVar();
  26231. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  26232. // dp = normalized distance from light to fragment position
  26233. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  26234. dp.addAssign( bias );
  26235. // bd3D = base direction 3D
  26236. const bd3D = lightToPosition.normalize();
  26237. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  26238. // percentage-closer filtering
  26239. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  26240. } );
  26241. return result;
  26242. } );
  26243. const _viewport = /*@__PURE__*/ new Vector4();
  26244. const _viewportSize = /*@__PURE__*/ new Vector2();
  26245. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  26246. /**
  26247. * Represents the shadow implementation for point light nodes.
  26248. *
  26249. * @augments module:ShadowNode~ShadowNode
  26250. */
  26251. class PointShadowNode extends ShadowNode {
  26252. static get type() {
  26253. return 'PointShadowNode';
  26254. }
  26255. /**
  26256. * Constructs a new point shadow node.
  26257. *
  26258. * @param {PointLight} light - The shadow casting point light.
  26259. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  26260. */
  26261. constructor( light, shadow = null ) {
  26262. super( light, shadow );
  26263. }
  26264. /**
  26265. * Overwrites the default implementation to return point light shadow specific
  26266. * filtering functions.
  26267. *
  26268. * @param {Number} type - The shadow type.
  26269. * @return {Function} The filtering function.
  26270. */
  26271. getShadowFilterFn( type ) {
  26272. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  26273. }
  26274. /**
  26275. * Overwrites the default implementation so the unaltered shadow position is used.
  26276. *
  26277. * @param {NodeBuilder} builder - A reference to the current node builder.
  26278. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  26279. * @return {Node<vec3>} The shadow coordinates.
  26280. */
  26281. setupShadowCoord( builder, shadowPosition ) {
  26282. return shadowPosition;
  26283. }
  26284. /**
  26285. * Overwrites the default implementation to only use point light specific
  26286. * shadow filter functions.
  26287. *
  26288. * @param {NodeBuilder} builder - A reference to the current node builder.
  26289. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  26290. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  26291. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  26292. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26293. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  26294. * @param {LightShadow} inputs.shadow - The light shadow.
  26295. * @return {Node<float>} The result node of the shadow filtering.
  26296. */
  26297. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  26298. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  26299. }
  26300. /**
  26301. * Overwrites the default implementation with point light specific
  26302. * rendering code.
  26303. *
  26304. * @param {NodeFrame} frame - A reference to the current node frame.
  26305. */
  26306. renderShadow( frame ) {
  26307. const { shadow, shadowMap, light } = this;
  26308. const { renderer, scene } = frame;
  26309. const shadowFrameExtents = shadow.getFrameExtents();
  26310. _shadowMapSize.copy( shadow.mapSize );
  26311. _shadowMapSize.multiply( shadowFrameExtents );
  26312. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  26313. _viewportSize.copy( shadow.mapSize );
  26314. //
  26315. const previousAutoClear = renderer.autoClear;
  26316. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  26317. const previousClearAlpha = renderer.getClearAlpha();
  26318. renderer.autoClear = false;
  26319. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  26320. renderer.clear();
  26321. const viewportCount = shadow.getViewportCount();
  26322. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  26323. const viewport = shadow.getViewport( vp );
  26324. const x = _viewportSize.x * viewport.x;
  26325. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  26326. _viewport.set(
  26327. x,
  26328. y,
  26329. _viewportSize.x * viewport.z,
  26330. _viewportSize.y * viewport.w
  26331. );
  26332. shadowMap.viewport.copy( _viewport );
  26333. shadow.updateMatrices( light, vp );
  26334. renderer.render( scene, shadow.camera );
  26335. }
  26336. //
  26337. renderer.autoClear = previousAutoClear;
  26338. renderer.setClearColor( previousClearColor, previousClearAlpha );
  26339. }
  26340. }
  26341. /**
  26342. * TSL function for creating an instance of `PointShadowNode`.
  26343. *
  26344. * @function
  26345. * @param {PointLight} light - The shadow casting point light.
  26346. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  26347. * @return {PointShadowNode} The created point shadow node.
  26348. */
  26349. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  26350. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  26351. const lightingModel = builder.context.lightingModel;
  26352. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  26353. const lightDirection = lVector.normalize();
  26354. const lightDistance = lVector.length();
  26355. const lightAttenuation = getDistanceAttenuation( {
  26356. lightDistance,
  26357. cutoffDistance,
  26358. decayExponent
  26359. } );
  26360. const lightColor = color.mul( lightAttenuation );
  26361. const reflectedLight = builder.context.reflectedLight;
  26362. lightingModel.direct( {
  26363. lightDirection,
  26364. lightColor,
  26365. reflectedLight
  26366. }, builder.stack, builder );
  26367. } );
  26368. /**
  26369. * Module for representing point lights as nodes.
  26370. *
  26371. * @augments AnalyticLightNode
  26372. */
  26373. class PointLightNode extends AnalyticLightNode {
  26374. static get type() {
  26375. return 'PointLightNode';
  26376. }
  26377. /**
  26378. * Constructs a new point light node.
  26379. *
  26380. * @param {PointLight?} [light=null] - The point light source.
  26381. */
  26382. constructor( light = null ) {
  26383. super( light );
  26384. /**
  26385. * Uniform node representing the cutoff distance.
  26386. *
  26387. * @type {UniformNode<float>}
  26388. */
  26389. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  26390. /**
  26391. * Uniform node representing the decay exponent.
  26392. *
  26393. * @type {UniformNode<float>}
  26394. */
  26395. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  26396. }
  26397. /**
  26398. * Overwritten to updated point light specific uniforms.
  26399. *
  26400. * @param {NodeFrame} frame - A reference to the current node frame.
  26401. */
  26402. update( frame ) {
  26403. const { light } = this;
  26404. super.update( frame );
  26405. this.cutoffDistanceNode.value = light.distance;
  26406. this.decayExponentNode.value = light.decay;
  26407. }
  26408. /**
  26409. * Overwritten to setup point light specific shadow.
  26410. *
  26411. * @return {PointShadowNode}
  26412. */
  26413. setupShadowNode() {
  26414. return pointShadow( this.light );
  26415. }
  26416. setup( builder ) {
  26417. super.setup( builder );
  26418. directPointLight( {
  26419. color: this.colorNode,
  26420. lightViewPosition: lightViewPosition( this.light ),
  26421. cutoffDistance: this.cutoffDistanceNode,
  26422. decayExponent: this.decayExponentNode
  26423. } ).append();
  26424. }
  26425. }
  26426. /** @module Procedural **/
  26427. /**
  26428. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  26429. *
  26430. * @method
  26431. * @param {Node<vec2>} coord - The uv coordinates.
  26432. * @return {Node<float>} The result data.
  26433. */
  26434. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  26435. const uv = coord.mul( 2.0 );
  26436. const cx = uv.x.floor();
  26437. const cy = uv.y.floor();
  26438. const result = cx.add( cy ).mod( 2.0 );
  26439. return result.sign();
  26440. } );
  26441. /** @module Shapes **/
  26442. /**
  26443. * Generates a circle based on the uv coordinates.
  26444. *
  26445. * @method
  26446. * @param {Node<vec2>} coord - The uv to generate the circle.
  26447. * @return {Node<float>} The circle shape.
  26448. */
  26449. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  26450. const alpha = float( 1 ).toVar();
  26451. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  26452. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  26453. const dlen = float( len2.fwidth() ).toVar();
  26454. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26455. } else {
  26456. len2.greaterThan( 1.0 ).discard();
  26457. }
  26458. return alpha;
  26459. } );
  26460. // Three.js Transpiler
  26461. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  26462. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  26463. const f = float( f_immutable ).toVar();
  26464. const t = float( t_immutable ).toVar();
  26465. const b = bool( b_immutable ).toVar();
  26466. return select( b, t, f );
  26467. } ).setLayout( {
  26468. name: 'mx_select',
  26469. type: 'float',
  26470. inputs: [
  26471. { name: 'b', type: 'bool' },
  26472. { name: 't', type: 'float' },
  26473. { name: 'f', type: 'float' }
  26474. ]
  26475. } );
  26476. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  26477. const b = bool( b_immutable ).toVar();
  26478. const val = float( val_immutable ).toVar();
  26479. return select( b, val.negate(), val );
  26480. } ).setLayout( {
  26481. name: 'mx_negate_if',
  26482. type: 'float',
  26483. inputs: [
  26484. { name: 'val', type: 'float' },
  26485. { name: 'b', type: 'bool' }
  26486. ]
  26487. } );
  26488. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26489. const x = float( x_immutable ).toVar();
  26490. return int( floor( x ) );
  26491. } ).setLayout( {
  26492. name: 'mx_floor',
  26493. type: 'int',
  26494. inputs: [
  26495. { name: 'x', type: 'float' }
  26496. ]
  26497. } );
  26498. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  26499. const x = float( x_immutable ).toVar();
  26500. i.assign( mx_floor( x ) );
  26501. return x.sub( float( i ) );
  26502. } );
  26503. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26504. const t = float( t_immutable ).toVar();
  26505. const s = float( s_immutable ).toVar();
  26506. const v3 = float( v3_immutable ).toVar();
  26507. const v2 = float( v2_immutable ).toVar();
  26508. const v1 = float( v1_immutable ).toVar();
  26509. const v0 = float( v0_immutable ).toVar();
  26510. const s1 = float( sub( 1.0, s ) ).toVar();
  26511. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26512. } ).setLayout( {
  26513. name: 'mx_bilerp_0',
  26514. type: 'float',
  26515. inputs: [
  26516. { name: 'v0', type: 'float' },
  26517. { name: 'v1', type: 'float' },
  26518. { name: 'v2', type: 'float' },
  26519. { name: 'v3', type: 'float' },
  26520. { name: 's', type: 'float' },
  26521. { name: 't', type: 'float' }
  26522. ]
  26523. } );
  26524. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26525. const t = float( t_immutable ).toVar();
  26526. const s = float( s_immutable ).toVar();
  26527. const v3 = vec3( v3_immutable ).toVar();
  26528. const v2 = vec3( v2_immutable ).toVar();
  26529. const v1 = vec3( v1_immutable ).toVar();
  26530. const v0 = vec3( v0_immutable ).toVar();
  26531. const s1 = float( sub( 1.0, s ) ).toVar();
  26532. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26533. } ).setLayout( {
  26534. name: 'mx_bilerp_1',
  26535. type: 'vec3',
  26536. inputs: [
  26537. { name: 'v0', type: 'vec3' },
  26538. { name: 'v1', type: 'vec3' },
  26539. { name: 'v2', type: 'vec3' },
  26540. { name: 'v3', type: 'vec3' },
  26541. { name: 's', type: 'float' },
  26542. { name: 't', type: 'float' }
  26543. ]
  26544. } );
  26545. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  26546. 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 ] ) => {
  26547. const r = float( r_immutable ).toVar();
  26548. const t = float( t_immutable ).toVar();
  26549. const s = float( s_immutable ).toVar();
  26550. const v7 = float( v7_immutable ).toVar();
  26551. const v6 = float( v6_immutable ).toVar();
  26552. const v5 = float( v5_immutable ).toVar();
  26553. const v4 = float( v4_immutable ).toVar();
  26554. const v3 = float( v3_immutable ).toVar();
  26555. const v2 = float( v2_immutable ).toVar();
  26556. const v1 = float( v1_immutable ).toVar();
  26557. const v0 = float( v0_immutable ).toVar();
  26558. const s1 = float( sub( 1.0, s ) ).toVar();
  26559. const t1 = float( sub( 1.0, t ) ).toVar();
  26560. const r1 = float( sub( 1.0, r ) ).toVar();
  26561. 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 ) ) ) ) ) );
  26562. } ).setLayout( {
  26563. name: 'mx_trilerp_0',
  26564. type: 'float',
  26565. inputs: [
  26566. { name: 'v0', type: 'float' },
  26567. { name: 'v1', type: 'float' },
  26568. { name: 'v2', type: 'float' },
  26569. { name: 'v3', type: 'float' },
  26570. { name: 'v4', type: 'float' },
  26571. { name: 'v5', type: 'float' },
  26572. { name: 'v6', type: 'float' },
  26573. { name: 'v7', type: 'float' },
  26574. { name: 's', type: 'float' },
  26575. { name: 't', type: 'float' },
  26576. { name: 'r', type: 'float' }
  26577. ]
  26578. } );
  26579. 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 ] ) => {
  26580. const r = float( r_immutable ).toVar();
  26581. const t = float( t_immutable ).toVar();
  26582. const s = float( s_immutable ).toVar();
  26583. const v7 = vec3( v7_immutable ).toVar();
  26584. const v6 = vec3( v6_immutable ).toVar();
  26585. const v5 = vec3( v5_immutable ).toVar();
  26586. const v4 = vec3( v4_immutable ).toVar();
  26587. const v3 = vec3( v3_immutable ).toVar();
  26588. const v2 = vec3( v2_immutable ).toVar();
  26589. const v1 = vec3( v1_immutable ).toVar();
  26590. const v0 = vec3( v0_immutable ).toVar();
  26591. const s1 = float( sub( 1.0, s ) ).toVar();
  26592. const t1 = float( sub( 1.0, t ) ).toVar();
  26593. const r1 = float( sub( 1.0, r ) ).toVar();
  26594. 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 ) ) ) ) ) );
  26595. } ).setLayout( {
  26596. name: 'mx_trilerp_1',
  26597. type: 'vec3',
  26598. inputs: [
  26599. { name: 'v0', type: 'vec3' },
  26600. { name: 'v1', type: 'vec3' },
  26601. { name: 'v2', type: 'vec3' },
  26602. { name: 'v3', type: 'vec3' },
  26603. { name: 'v4', type: 'vec3' },
  26604. { name: 'v5', type: 'vec3' },
  26605. { name: 'v6', type: 'vec3' },
  26606. { name: 'v7', type: 'vec3' },
  26607. { name: 's', type: 'float' },
  26608. { name: 't', type: 'float' },
  26609. { name: 'r', type: 'float' }
  26610. ]
  26611. } );
  26612. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  26613. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26614. const y = float( y_immutable ).toVar();
  26615. const x = float( x_immutable ).toVar();
  26616. const hash = uint( hash_immutable ).toVar();
  26617. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  26618. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  26619. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  26620. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26621. } ).setLayout( {
  26622. name: 'mx_gradient_float_0',
  26623. type: 'float',
  26624. inputs: [
  26625. { name: 'hash', type: 'uint' },
  26626. { name: 'x', type: 'float' },
  26627. { name: 'y', type: 'float' }
  26628. ]
  26629. } );
  26630. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26631. const z = float( z_immutable ).toVar();
  26632. const y = float( y_immutable ).toVar();
  26633. const x = float( x_immutable ).toVar();
  26634. const hash = uint( hash_immutable ).toVar();
  26635. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  26636. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  26637. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  26638. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26639. } ).setLayout( {
  26640. name: 'mx_gradient_float_1',
  26641. type: 'float',
  26642. inputs: [
  26643. { name: 'hash', type: 'uint' },
  26644. { name: 'x', type: 'float' },
  26645. { name: 'y', type: 'float' },
  26646. { name: 'z', type: 'float' }
  26647. ]
  26648. } );
  26649. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  26650. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26651. const y = float( y_immutable ).toVar();
  26652. const x = float( x_immutable ).toVar();
  26653. const hash = uvec3( hash_immutable ).toVar();
  26654. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  26655. } ).setLayout( {
  26656. name: 'mx_gradient_vec3_0',
  26657. type: 'vec3',
  26658. inputs: [
  26659. { name: 'hash', type: 'uvec3' },
  26660. { name: 'x', type: 'float' },
  26661. { name: 'y', type: 'float' }
  26662. ]
  26663. } );
  26664. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26665. const z = float( z_immutable ).toVar();
  26666. const y = float( y_immutable ).toVar();
  26667. const x = float( x_immutable ).toVar();
  26668. const hash = uvec3( hash_immutable ).toVar();
  26669. 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 ) );
  26670. } ).setLayout( {
  26671. name: 'mx_gradient_vec3_1',
  26672. type: 'vec3',
  26673. inputs: [
  26674. { name: 'hash', type: 'uvec3' },
  26675. { name: 'x', type: 'float' },
  26676. { name: 'y', type: 'float' },
  26677. { name: 'z', type: 'float' }
  26678. ]
  26679. } );
  26680. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  26681. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26682. const v = float( v_immutable ).toVar();
  26683. return mul( 0.6616, v );
  26684. } ).setLayout( {
  26685. name: 'mx_gradient_scale2d_0',
  26686. type: 'float',
  26687. inputs: [
  26688. { name: 'v', type: 'float' }
  26689. ]
  26690. } );
  26691. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26692. const v = float( v_immutable ).toVar();
  26693. return mul( 0.9820, v );
  26694. } ).setLayout( {
  26695. name: 'mx_gradient_scale3d_0',
  26696. type: 'float',
  26697. inputs: [
  26698. { name: 'v', type: 'float' }
  26699. ]
  26700. } );
  26701. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26702. const v = vec3( v_immutable ).toVar();
  26703. return mul( 0.6616, v );
  26704. } ).setLayout( {
  26705. name: 'mx_gradient_scale2d_1',
  26706. type: 'vec3',
  26707. inputs: [
  26708. { name: 'v', type: 'vec3' }
  26709. ]
  26710. } );
  26711. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  26712. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26713. const v = vec3( v_immutable ).toVar();
  26714. return mul( 0.9820, v );
  26715. } ).setLayout( {
  26716. name: 'mx_gradient_scale3d_1',
  26717. type: 'vec3',
  26718. inputs: [
  26719. { name: 'v', type: 'vec3' }
  26720. ]
  26721. } );
  26722. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  26723. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  26724. const k = int( k_immutable ).toVar();
  26725. const x = uint( x_immutable ).toVar();
  26726. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  26727. } ).setLayout( {
  26728. name: 'mx_rotl32',
  26729. type: 'uint',
  26730. inputs: [
  26731. { name: 'x', type: 'uint' },
  26732. { name: 'k', type: 'int' }
  26733. ]
  26734. } );
  26735. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  26736. a.subAssign( c );
  26737. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26738. c.addAssign( b );
  26739. b.subAssign( a );
  26740. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26741. a.addAssign( c );
  26742. c.subAssign( b );
  26743. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26744. b.addAssign( a );
  26745. a.subAssign( c );
  26746. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26747. c.addAssign( b );
  26748. b.subAssign( a );
  26749. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26750. a.addAssign( c );
  26751. c.subAssign( b );
  26752. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26753. b.addAssign( a );
  26754. } );
  26755. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26756. const c = uint( c_immutable ).toVar();
  26757. const b = uint( b_immutable ).toVar();
  26758. const a = uint( a_immutable ).toVar();
  26759. c.bitXorAssign( b );
  26760. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26761. a.bitXorAssign( c );
  26762. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26763. b.bitXorAssign( a );
  26764. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26765. c.bitXorAssign( b );
  26766. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26767. a.bitXorAssign( c );
  26768. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26769. b.bitXorAssign( a );
  26770. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26771. c.bitXorAssign( b );
  26772. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26773. return c;
  26774. } ).setLayout( {
  26775. name: 'mx_bjfinal',
  26776. type: 'uint',
  26777. inputs: [
  26778. { name: 'a', type: 'uint' },
  26779. { name: 'b', type: 'uint' },
  26780. { name: 'c', type: 'uint' }
  26781. ]
  26782. } );
  26783. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26784. const bits = uint( bits_immutable ).toVar();
  26785. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26786. } ).setLayout( {
  26787. name: 'mx_bits_to_01',
  26788. type: 'float',
  26789. inputs: [
  26790. { name: 'bits', type: 'uint' }
  26791. ]
  26792. } );
  26793. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26794. const t = float( t_immutable ).toVar();
  26795. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26796. } ).setLayout( {
  26797. name: 'mx_fade',
  26798. type: 'float',
  26799. inputs: [
  26800. { name: 't', type: 'float' }
  26801. ]
  26802. } );
  26803. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26804. const x = int( x_immutable ).toVar();
  26805. const len = uint( uint( 1 ) ).toVar();
  26806. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26807. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26808. } ).setLayout( {
  26809. name: 'mx_hash_int_0',
  26810. type: 'uint',
  26811. inputs: [
  26812. { name: 'x', type: 'int' }
  26813. ]
  26814. } );
  26815. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26816. const y = int( y_immutable ).toVar();
  26817. const x = int( x_immutable ).toVar();
  26818. const len = uint( uint( 2 ) ).toVar();
  26819. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26820. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26821. a.addAssign( uint( x ) );
  26822. b.addAssign( uint( y ) );
  26823. return mx_bjfinal( a, b, c );
  26824. } ).setLayout( {
  26825. name: 'mx_hash_int_1',
  26826. type: 'uint',
  26827. inputs: [
  26828. { name: 'x', type: 'int' },
  26829. { name: 'y', type: 'int' }
  26830. ]
  26831. } );
  26832. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26833. const z = int( z_immutable ).toVar();
  26834. const y = int( y_immutable ).toVar();
  26835. const x = int( x_immutable ).toVar();
  26836. const len = uint( uint( 3 ) ).toVar();
  26837. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26838. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26839. a.addAssign( uint( x ) );
  26840. b.addAssign( uint( y ) );
  26841. c.addAssign( uint( z ) );
  26842. return mx_bjfinal( a, b, c );
  26843. } ).setLayout( {
  26844. name: 'mx_hash_int_2',
  26845. type: 'uint',
  26846. inputs: [
  26847. { name: 'x', type: 'int' },
  26848. { name: 'y', type: 'int' },
  26849. { name: 'z', type: 'int' }
  26850. ]
  26851. } );
  26852. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26853. const xx = int( xx_immutable ).toVar();
  26854. const z = int( z_immutable ).toVar();
  26855. const y = int( y_immutable ).toVar();
  26856. const x = int( x_immutable ).toVar();
  26857. const len = uint( uint( 4 ) ).toVar();
  26858. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26859. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26860. a.addAssign( uint( x ) );
  26861. b.addAssign( uint( y ) );
  26862. c.addAssign( uint( z ) );
  26863. mx_bjmix( a, b, c );
  26864. a.addAssign( uint( xx ) );
  26865. return mx_bjfinal( a, b, c );
  26866. } ).setLayout( {
  26867. name: 'mx_hash_int_3',
  26868. type: 'uint',
  26869. inputs: [
  26870. { name: 'x', type: 'int' },
  26871. { name: 'y', type: 'int' },
  26872. { name: 'z', type: 'int' },
  26873. { name: 'xx', type: 'int' }
  26874. ]
  26875. } );
  26876. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26877. const yy = int( yy_immutable ).toVar();
  26878. const xx = int( xx_immutable ).toVar();
  26879. const z = int( z_immutable ).toVar();
  26880. const y = int( y_immutable ).toVar();
  26881. const x = int( x_immutable ).toVar();
  26882. const len = uint( uint( 5 ) ).toVar();
  26883. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26884. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26885. a.addAssign( uint( x ) );
  26886. b.addAssign( uint( y ) );
  26887. c.addAssign( uint( z ) );
  26888. mx_bjmix( a, b, c );
  26889. a.addAssign( uint( xx ) );
  26890. b.addAssign( uint( yy ) );
  26891. return mx_bjfinal( a, b, c );
  26892. } ).setLayout( {
  26893. name: 'mx_hash_int_4',
  26894. type: 'uint',
  26895. inputs: [
  26896. { name: 'x', type: 'int' },
  26897. { name: 'y', type: 'int' },
  26898. { name: 'z', type: 'int' },
  26899. { name: 'xx', type: 'int' },
  26900. { name: 'yy', type: 'int' }
  26901. ]
  26902. } );
  26903. 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 ] );
  26904. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26905. const y = int( y_immutable ).toVar();
  26906. const x = int( x_immutable ).toVar();
  26907. const h = uint( mx_hash_int( x, y ) ).toVar();
  26908. const result = uvec3().toVar();
  26909. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26910. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26911. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26912. return result;
  26913. } ).setLayout( {
  26914. name: 'mx_hash_vec3_0',
  26915. type: 'uvec3',
  26916. inputs: [
  26917. { name: 'x', type: 'int' },
  26918. { name: 'y', type: 'int' }
  26919. ]
  26920. } );
  26921. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26922. const z = int( z_immutable ).toVar();
  26923. const y = int( y_immutable ).toVar();
  26924. const x = int( x_immutable ).toVar();
  26925. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26926. const result = uvec3().toVar();
  26927. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26928. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26929. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26930. return result;
  26931. } ).setLayout( {
  26932. name: 'mx_hash_vec3_1',
  26933. type: 'uvec3',
  26934. inputs: [
  26935. { name: 'x', type: 'int' },
  26936. { name: 'y', type: 'int' },
  26937. { name: 'z', type: 'int' }
  26938. ]
  26939. } );
  26940. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26941. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26942. const p = vec2( p_immutable ).toVar();
  26943. const X = int().toVar(), Y = int().toVar();
  26944. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26945. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26946. const u = float( mx_fade( fx ) ).toVar();
  26947. const v = float( mx_fade( fy ) ).toVar();
  26948. 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();
  26949. return mx_gradient_scale2d( result );
  26950. } ).setLayout( {
  26951. name: 'mx_perlin_noise_float_0',
  26952. type: 'float',
  26953. inputs: [
  26954. { name: 'p', type: 'vec2' }
  26955. ]
  26956. } );
  26957. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26958. const p = vec3( p_immutable ).toVar();
  26959. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26960. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26961. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26962. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26963. const u = float( mx_fade( fx ) ).toVar();
  26964. const v = float( mx_fade( fy ) ).toVar();
  26965. const w = float( mx_fade( fz ) ).toVar();
  26966. 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();
  26967. return mx_gradient_scale3d( result );
  26968. } ).setLayout( {
  26969. name: 'mx_perlin_noise_float_1',
  26970. type: 'float',
  26971. inputs: [
  26972. { name: 'p', type: 'vec3' }
  26973. ]
  26974. } );
  26975. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26976. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26977. const p = vec2( p_immutable ).toVar();
  26978. const X = int().toVar(), Y = int().toVar();
  26979. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26980. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26981. const u = float( mx_fade( fx ) ).toVar();
  26982. const v = float( mx_fade( fy ) ).toVar();
  26983. 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();
  26984. return mx_gradient_scale2d( result );
  26985. } ).setLayout( {
  26986. name: 'mx_perlin_noise_vec3_0',
  26987. type: 'vec3',
  26988. inputs: [
  26989. { name: 'p', type: 'vec2' }
  26990. ]
  26991. } );
  26992. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26993. const p = vec3( p_immutable ).toVar();
  26994. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26995. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26996. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26997. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26998. const u = float( mx_fade( fx ) ).toVar();
  26999. const v = float( mx_fade( fy ) ).toVar();
  27000. const w = float( mx_fade( fz ) ).toVar();
  27001. 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();
  27002. return mx_gradient_scale3d( result );
  27003. } ).setLayout( {
  27004. name: 'mx_perlin_noise_vec3_1',
  27005. type: 'vec3',
  27006. inputs: [
  27007. { name: 'p', type: 'vec3' }
  27008. ]
  27009. } );
  27010. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  27011. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27012. const p = float( p_immutable ).toVar();
  27013. const ix = int( mx_floor( p ) ).toVar();
  27014. return mx_bits_to_01( mx_hash_int( ix ) );
  27015. } ).setLayout( {
  27016. name: 'mx_cell_noise_float_0',
  27017. type: 'float',
  27018. inputs: [
  27019. { name: 'p', type: 'float' }
  27020. ]
  27021. } );
  27022. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27023. const p = vec2( p_immutable ).toVar();
  27024. const ix = int( mx_floor( p.x ) ).toVar();
  27025. const iy = int( mx_floor( p.y ) ).toVar();
  27026. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  27027. } ).setLayout( {
  27028. name: 'mx_cell_noise_float_1',
  27029. type: 'float',
  27030. inputs: [
  27031. { name: 'p', type: 'vec2' }
  27032. ]
  27033. } );
  27034. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27035. const p = vec3( p_immutable ).toVar();
  27036. const ix = int( mx_floor( p.x ) ).toVar();
  27037. const iy = int( mx_floor( p.y ) ).toVar();
  27038. const iz = int( mx_floor( p.z ) ).toVar();
  27039. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  27040. } ).setLayout( {
  27041. name: 'mx_cell_noise_float_2',
  27042. type: 'float',
  27043. inputs: [
  27044. { name: 'p', type: 'vec3' }
  27045. ]
  27046. } );
  27047. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27048. const p = vec4( p_immutable ).toVar();
  27049. const ix = int( mx_floor( p.x ) ).toVar();
  27050. const iy = int( mx_floor( p.y ) ).toVar();
  27051. const iz = int( mx_floor( p.z ) ).toVar();
  27052. const iw = int( mx_floor( p.w ) ).toVar();
  27053. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  27054. } ).setLayout( {
  27055. name: 'mx_cell_noise_float_3',
  27056. type: 'float',
  27057. inputs: [
  27058. { name: 'p', type: 'vec4' }
  27059. ]
  27060. } );
  27061. 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 ] );
  27062. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27063. const p = float( p_immutable ).toVar();
  27064. const ix = int( mx_floor( p ) ).toVar();
  27065. 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 ) ) ) );
  27066. } ).setLayout( {
  27067. name: 'mx_cell_noise_vec3_0',
  27068. type: 'vec3',
  27069. inputs: [
  27070. { name: 'p', type: 'float' }
  27071. ]
  27072. } );
  27073. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27074. const p = vec2( p_immutable ).toVar();
  27075. const ix = int( mx_floor( p.x ) ).toVar();
  27076. const iy = int( mx_floor( p.y ) ).toVar();
  27077. 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 ) ) ) );
  27078. } ).setLayout( {
  27079. name: 'mx_cell_noise_vec3_1',
  27080. type: 'vec3',
  27081. inputs: [
  27082. { name: 'p', type: 'vec2' }
  27083. ]
  27084. } );
  27085. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27086. const p = vec3( p_immutable ).toVar();
  27087. const ix = int( mx_floor( p.x ) ).toVar();
  27088. const iy = int( mx_floor( p.y ) ).toVar();
  27089. const iz = int( mx_floor( p.z ) ).toVar();
  27090. 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 ) ) ) );
  27091. } ).setLayout( {
  27092. name: 'mx_cell_noise_vec3_2',
  27093. type: 'vec3',
  27094. inputs: [
  27095. { name: 'p', type: 'vec3' }
  27096. ]
  27097. } );
  27098. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  27099. const p = vec4( p_immutable ).toVar();
  27100. const ix = int( mx_floor( p.x ) ).toVar();
  27101. const iy = int( mx_floor( p.y ) ).toVar();
  27102. const iz = int( mx_floor( p.z ) ).toVar();
  27103. const iw = int( mx_floor( p.w ) ).toVar();
  27104. 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 ) ) ) );
  27105. } ).setLayout( {
  27106. name: 'mx_cell_noise_vec3_3',
  27107. type: 'vec3',
  27108. inputs: [
  27109. { name: 'p', type: 'vec4' }
  27110. ]
  27111. } );
  27112. 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 ] );
  27113. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27114. const diminish = float( diminish_immutable ).toVar();
  27115. const lacunarity = float( lacunarity_immutable ).toVar();
  27116. const octaves = int( octaves_immutable ).toVar();
  27117. const p = vec3( p_immutable ).toVar();
  27118. const result = float( 0.0 ).toVar();
  27119. const amplitude = float( 1.0 ).toVar();
  27120. Loop( octaves, () => {
  27121. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  27122. amplitude.mulAssign( diminish );
  27123. p.mulAssign( lacunarity );
  27124. } );
  27125. return result;
  27126. } ).setLayout( {
  27127. name: 'mx_fractal_noise_float',
  27128. type: 'float',
  27129. inputs: [
  27130. { name: 'p', type: 'vec3' },
  27131. { name: 'octaves', type: 'int' },
  27132. { name: 'lacunarity', type: 'float' },
  27133. { name: 'diminish', type: 'float' }
  27134. ]
  27135. } );
  27136. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27137. const diminish = float( diminish_immutable ).toVar();
  27138. const lacunarity = float( lacunarity_immutable ).toVar();
  27139. const octaves = int( octaves_immutable ).toVar();
  27140. const p = vec3( p_immutable ).toVar();
  27141. const result = vec3( 0.0 ).toVar();
  27142. const amplitude = float( 1.0 ).toVar();
  27143. Loop( octaves, () => {
  27144. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  27145. amplitude.mulAssign( diminish );
  27146. p.mulAssign( lacunarity );
  27147. } );
  27148. return result;
  27149. } ).setLayout( {
  27150. name: 'mx_fractal_noise_vec3',
  27151. type: 'vec3',
  27152. inputs: [
  27153. { name: 'p', type: 'vec3' },
  27154. { name: 'octaves', type: 'int' },
  27155. { name: 'lacunarity', type: 'float' },
  27156. { name: 'diminish', type: 'float' }
  27157. ]
  27158. } );
  27159. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27160. const diminish = float( diminish_immutable ).toVar();
  27161. const lacunarity = float( lacunarity_immutable ).toVar();
  27162. const octaves = int( octaves_immutable ).toVar();
  27163. const p = vec3( p_immutable ).toVar();
  27164. 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 ) );
  27165. } ).setLayout( {
  27166. name: 'mx_fractal_noise_vec2',
  27167. type: 'vec2',
  27168. inputs: [
  27169. { name: 'p', type: 'vec3' },
  27170. { name: 'octaves', type: 'int' },
  27171. { name: 'lacunarity', type: 'float' },
  27172. { name: 'diminish', type: 'float' }
  27173. ]
  27174. } );
  27175. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  27176. const diminish = float( diminish_immutable ).toVar();
  27177. const lacunarity = float( lacunarity_immutable ).toVar();
  27178. const octaves = int( octaves_immutable ).toVar();
  27179. const p = vec3( p_immutable ).toVar();
  27180. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  27181. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  27182. return vec4( c, f );
  27183. } ).setLayout( {
  27184. name: 'mx_fractal_noise_vec4',
  27185. type: 'vec4',
  27186. inputs: [
  27187. { name: 'p', type: 'vec3' },
  27188. { name: 'octaves', type: 'int' },
  27189. { name: 'lacunarity', type: 'float' },
  27190. { name: 'diminish', type: 'float' }
  27191. ]
  27192. } );
  27193. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  27194. const metric = int( metric_immutable ).toVar();
  27195. const jitter = float( jitter_immutable ).toVar();
  27196. const yoff = int( yoff_immutable ).toVar();
  27197. const xoff = int( xoff_immutable ).toVar();
  27198. const y = int( y_immutable ).toVar();
  27199. const x = int( x_immutable ).toVar();
  27200. const p = vec2( p_immutable ).toVar();
  27201. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  27202. const off = vec2( tmp.x, tmp.y ).toVar();
  27203. off.subAssign( 0.5 );
  27204. off.mulAssign( jitter );
  27205. off.addAssign( 0.5 );
  27206. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  27207. const diff = vec2( cellpos.sub( p ) ).toVar();
  27208. If( metric.equal( int( 2 ) ), () => {
  27209. return abs( diff.x ).add( abs( diff.y ) );
  27210. } );
  27211. If( metric.equal( int( 3 ) ), () => {
  27212. return max$1( abs( diff.x ), abs( diff.y ) );
  27213. } );
  27214. return dot( diff, diff );
  27215. } ).setLayout( {
  27216. name: 'mx_worley_distance_0',
  27217. type: 'float',
  27218. inputs: [
  27219. { name: 'p', type: 'vec2' },
  27220. { name: 'x', type: 'int' },
  27221. { name: 'y', type: 'int' },
  27222. { name: 'xoff', type: 'int' },
  27223. { name: 'yoff', type: 'int' },
  27224. { name: 'jitter', type: 'float' },
  27225. { name: 'metric', type: 'int' }
  27226. ]
  27227. } );
  27228. 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 ] ) => {
  27229. const metric = int( metric_immutable ).toVar();
  27230. const jitter = float( jitter_immutable ).toVar();
  27231. const zoff = int( zoff_immutable ).toVar();
  27232. const yoff = int( yoff_immutable ).toVar();
  27233. const xoff = int( xoff_immutable ).toVar();
  27234. const z = int( z_immutable ).toVar();
  27235. const y = int( y_immutable ).toVar();
  27236. const x = int( x_immutable ).toVar();
  27237. const p = vec3( p_immutable ).toVar();
  27238. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  27239. off.subAssign( 0.5 );
  27240. off.mulAssign( jitter );
  27241. off.addAssign( 0.5 );
  27242. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  27243. const diff = vec3( cellpos.sub( p ) ).toVar();
  27244. If( metric.equal( int( 2 ) ), () => {
  27245. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  27246. } );
  27247. If( metric.equal( int( 3 ) ), () => {
  27248. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  27249. } );
  27250. return dot( diff, diff );
  27251. } ).setLayout( {
  27252. name: 'mx_worley_distance_1',
  27253. type: 'float',
  27254. inputs: [
  27255. { name: 'p', type: 'vec3' },
  27256. { name: 'x', type: 'int' },
  27257. { name: 'y', type: 'int' },
  27258. { name: 'z', type: 'int' },
  27259. { name: 'xoff', type: 'int' },
  27260. { name: 'yoff', type: 'int' },
  27261. { name: 'zoff', type: 'int' },
  27262. { name: 'jitter', type: 'float' },
  27263. { name: 'metric', type: 'int' }
  27264. ]
  27265. } );
  27266. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  27267. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27268. const metric = int( metric_immutable ).toVar();
  27269. const jitter = float( jitter_immutable ).toVar();
  27270. const p = vec2( p_immutable ).toVar();
  27271. const X = int().toVar(), Y = int().toVar();
  27272. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27273. const sqdist = float( 1e6 ).toVar();
  27274. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27275. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27276. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27277. sqdist.assign( min$1( sqdist, dist ) );
  27278. } );
  27279. } );
  27280. If( metric.equal( int( 0 ) ), () => {
  27281. sqdist.assign( sqrt( sqdist ) );
  27282. } );
  27283. return sqdist;
  27284. } ).setLayout( {
  27285. name: 'mx_worley_noise_float_0',
  27286. type: 'float',
  27287. inputs: [
  27288. { name: 'p', type: 'vec2' },
  27289. { name: 'jitter', type: 'float' },
  27290. { name: 'metric', type: 'int' }
  27291. ]
  27292. } );
  27293. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27294. const metric = int( metric_immutable ).toVar();
  27295. const jitter = float( jitter_immutable ).toVar();
  27296. const p = vec2( p_immutable ).toVar();
  27297. const X = int().toVar(), Y = int().toVar();
  27298. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27299. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27300. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27301. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27302. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27303. If( dist.lessThan( sqdist.x ), () => {
  27304. sqdist.y.assign( sqdist.x );
  27305. sqdist.x.assign( dist );
  27306. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27307. sqdist.y.assign( dist );
  27308. } );
  27309. } );
  27310. } );
  27311. If( metric.equal( int( 0 ) ), () => {
  27312. sqdist.assign( sqrt( sqdist ) );
  27313. } );
  27314. return sqdist;
  27315. } ).setLayout( {
  27316. name: 'mx_worley_noise_vec2_0',
  27317. type: 'vec2',
  27318. inputs: [
  27319. { name: 'p', type: 'vec2' },
  27320. { name: 'jitter', type: 'float' },
  27321. { name: 'metric', type: 'int' }
  27322. ]
  27323. } );
  27324. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27325. const metric = int( metric_immutable ).toVar();
  27326. const jitter = float( jitter_immutable ).toVar();
  27327. const p = vec2( p_immutable ).toVar();
  27328. const X = int().toVar(), Y = int().toVar();
  27329. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  27330. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27331. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27332. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27333. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  27334. If( dist.lessThan( sqdist.x ), () => {
  27335. sqdist.z.assign( sqdist.y );
  27336. sqdist.y.assign( sqdist.x );
  27337. sqdist.x.assign( dist );
  27338. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27339. sqdist.z.assign( sqdist.y );
  27340. sqdist.y.assign( dist );
  27341. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27342. sqdist.z.assign( dist );
  27343. } );
  27344. } );
  27345. } );
  27346. If( metric.equal( int( 0 ) ), () => {
  27347. sqdist.assign( sqrt( sqdist ) );
  27348. } );
  27349. return sqdist;
  27350. } ).setLayout( {
  27351. name: 'mx_worley_noise_vec3_0',
  27352. type: 'vec3',
  27353. inputs: [
  27354. { name: 'p', type: 'vec2' },
  27355. { name: 'jitter', type: 'float' },
  27356. { name: 'metric', type: 'int' }
  27357. ]
  27358. } );
  27359. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27360. const metric = int( metric_immutable ).toVar();
  27361. const jitter = float( jitter_immutable ).toVar();
  27362. const p = vec3( p_immutable ).toVar();
  27363. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27364. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27365. const sqdist = float( 1e6 ).toVar();
  27366. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27367. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27368. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27369. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27370. sqdist.assign( min$1( sqdist, dist ) );
  27371. } );
  27372. } );
  27373. } );
  27374. If( metric.equal( int( 0 ) ), () => {
  27375. sqdist.assign( sqrt( sqdist ) );
  27376. } );
  27377. return sqdist;
  27378. } ).setLayout( {
  27379. name: 'mx_worley_noise_float_1',
  27380. type: 'float',
  27381. inputs: [
  27382. { name: 'p', type: 'vec3' },
  27383. { name: 'jitter', type: 'float' },
  27384. { name: 'metric', type: 'int' }
  27385. ]
  27386. } );
  27387. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  27388. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27389. const metric = int( metric_immutable ).toVar();
  27390. const jitter = float( jitter_immutable ).toVar();
  27391. const p = vec3( p_immutable ).toVar();
  27392. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27393. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27394. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27395. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27396. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27397. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27398. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27399. If( dist.lessThan( sqdist.x ), () => {
  27400. sqdist.y.assign( sqdist.x );
  27401. sqdist.x.assign( dist );
  27402. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27403. sqdist.y.assign( dist );
  27404. } );
  27405. } );
  27406. } );
  27407. } );
  27408. If( metric.equal( int( 0 ) ), () => {
  27409. sqdist.assign( sqrt( sqdist ) );
  27410. } );
  27411. return sqdist;
  27412. } ).setLayout( {
  27413. name: 'mx_worley_noise_vec2_1',
  27414. type: 'vec2',
  27415. inputs: [
  27416. { name: 'p', type: 'vec3' },
  27417. { name: 'jitter', type: 'float' },
  27418. { name: 'metric', type: 'int' }
  27419. ]
  27420. } );
  27421. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  27422. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27423. const metric = int( metric_immutable ).toVar();
  27424. const jitter = float( jitter_immutable ).toVar();
  27425. const p = vec3( p_immutable ).toVar();
  27426. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27427. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27428. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27429. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27430. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27431. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27432. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27433. If( dist.lessThan( sqdist.x ), () => {
  27434. sqdist.z.assign( sqdist.y );
  27435. sqdist.y.assign( sqdist.x );
  27436. sqdist.x.assign( dist );
  27437. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27438. sqdist.z.assign( sqdist.y );
  27439. sqdist.y.assign( dist );
  27440. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27441. sqdist.z.assign( dist );
  27442. } );
  27443. } );
  27444. } );
  27445. } );
  27446. If( metric.equal( int( 0 ) ), () => {
  27447. sqdist.assign( sqrt( sqdist ) );
  27448. } );
  27449. return sqdist;
  27450. } ).setLayout( {
  27451. name: 'mx_worley_noise_vec3_1',
  27452. type: 'vec3',
  27453. inputs: [
  27454. { name: 'p', type: 'vec3' },
  27455. { name: 'jitter', type: 'float' },
  27456. { name: 'metric', type: 'int' }
  27457. ]
  27458. } );
  27459. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  27460. // Three.js Transpiler
  27461. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  27462. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  27463. const s = hsv.y;
  27464. const v = hsv.z;
  27465. const result = vec3().toVar();
  27466. If( s.lessThan( 0.0001 ), () => {
  27467. result.assign( vec3( v, v, v ) );
  27468. } ).Else( () => {
  27469. let h = hsv.x;
  27470. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  27471. const hi = int( trunc( h ) );
  27472. const f = h.sub( float( hi ) );
  27473. const p = v.mul( s.oneMinus() );
  27474. const q = v.mul( s.mul( f ).oneMinus() );
  27475. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  27476. If( hi.equal( int( 0 ) ), () => {
  27477. result.assign( vec3( v, t, p ) );
  27478. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  27479. result.assign( vec3( q, v, p ) );
  27480. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  27481. result.assign( vec3( p, v, t ) );
  27482. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  27483. result.assign( vec3( p, q, v ) );
  27484. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  27485. result.assign( vec3( t, p, v ) );
  27486. } ).Else( () => {
  27487. result.assign( vec3( v, p, q ) );
  27488. } );
  27489. } );
  27490. return result;
  27491. } ).setLayout( {
  27492. name: 'mx_hsvtorgb',
  27493. type: 'vec3',
  27494. inputs: [
  27495. { name: 'hsv', type: 'vec3' }
  27496. ]
  27497. } );
  27498. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  27499. const c = vec3( c_immutable ).toVar();
  27500. const r = float( c.x ).toVar();
  27501. const g = float( c.y ).toVar();
  27502. const b = float( c.z ).toVar();
  27503. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  27504. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  27505. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  27506. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  27507. v.assign( maxcomp );
  27508. If( maxcomp.greaterThan( 0.0 ), () => {
  27509. s.assign( delta.div( maxcomp ) );
  27510. } ).Else( () => {
  27511. s.assign( 0.0 );
  27512. } );
  27513. If( s.lessThanEqual( 0.0 ), () => {
  27514. h.assign( 0.0 );
  27515. } ).Else( () => {
  27516. If( r.greaterThanEqual( maxcomp ), () => {
  27517. h.assign( g.sub( b ).div( delta ) );
  27518. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  27519. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  27520. } ).Else( () => {
  27521. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  27522. } );
  27523. h.mulAssign( 1.0 / 6.0 );
  27524. If( h.lessThan( 0.0 ), () => {
  27525. h.addAssign( 1.0 );
  27526. } );
  27527. } );
  27528. return vec3( h, s, v );
  27529. } ).setLayout( {
  27530. name: 'mx_rgbtohsv',
  27531. type: 'vec3',
  27532. inputs: [
  27533. { name: 'c', type: 'vec3' }
  27534. ]
  27535. } );
  27536. // Three.js Transpiler
  27537. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  27538. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  27539. const color = vec3( color_immutable ).toVar();
  27540. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  27541. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  27542. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  27543. return mix( linSeg, powSeg, isAbove );
  27544. } ).setLayout( {
  27545. name: 'mx_srgb_texture_to_lin_rec709',
  27546. type: 'vec3',
  27547. inputs: [
  27548. { name: 'color', type: 'vec3' }
  27549. ]
  27550. } );
  27551. const mx_aastep = ( threshold, value ) => {
  27552. threshold = float( threshold );
  27553. value = float( value );
  27554. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  27555. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  27556. };
  27557. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  27558. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  27559. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  27560. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  27561. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  27562. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  27563. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  27564. const mx_safepower = ( in1, in2 = 1 ) => {
  27565. in1 = float( in1 );
  27566. return in1.abs().pow( in2 ).mul( in1.sign() );
  27567. };
  27568. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  27569. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27570. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27571. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27572. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  27573. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  27574. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  27575. return noise_vec4.mul( amplitude ).add( pivot );
  27576. };
  27577. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27578. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27579. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27580. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  27581. 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 );
  27582. 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 );
  27583. 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 );
  27584. 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 );
  27585. /** @module getParallaxCorrectNormal **/
  27586. /**
  27587. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  27588. *
  27589. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  27590. *
  27591. * ```js
  27592. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  27593. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  27594. * ```
  27595. * @function
  27596. * @param {Node<vec3>} normal - The normal to correct.
  27597. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  27598. * @param {Node<vec3>} cubePos - The cube position.
  27599. * @return {Node<vec3>} The parallax corrected normal.
  27600. */
  27601. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  27602. const nDir = normalize( normal ).toVar( 'nDir' );
  27603. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  27604. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  27605. const rbminmax = vec3().toVar( 'rbminmax' );
  27606. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  27607. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  27608. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  27609. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  27610. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  27611. return boxIntersection.sub( cubePos );
  27612. } );
  27613. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  27614. // normal is assumed to have unit length
  27615. const x = normal.x, y = normal.y, z = normal.z;
  27616. // band 0
  27617. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  27618. // band 1
  27619. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  27620. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  27621. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  27622. // band 2
  27623. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  27624. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  27625. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  27626. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  27627. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  27628. return result;
  27629. } );
  27630. // constants
  27631. var TSL = /*#__PURE__*/Object.freeze({
  27632. __proto__: null,
  27633. BRDF_GGX: BRDF_GGX,
  27634. BRDF_Lambert: BRDF_Lambert,
  27635. BasicShadowFilter: BasicShadowFilter,
  27636. Break: Break,
  27637. Const: Const,
  27638. Continue: Continue,
  27639. DFGApprox: DFGApprox,
  27640. D_GGX: D_GGX,
  27641. Discard: Discard,
  27642. EPSILON: EPSILON,
  27643. F_Schlick: F_Schlick,
  27644. Fn: Fn,
  27645. INFINITY: INFINITY,
  27646. If: If,
  27647. Loop: Loop,
  27648. NodeAccess: NodeAccess,
  27649. NodeShaderStage: NodeShaderStage,
  27650. NodeType: NodeType,
  27651. NodeUpdateType: NodeUpdateType,
  27652. PCFShadowFilter: PCFShadowFilter,
  27653. PCFSoftShadowFilter: PCFSoftShadowFilter,
  27654. PI: PI,
  27655. PI2: PI2,
  27656. Return: Return,
  27657. Schlick_to_F0: Schlick_to_F0,
  27658. ScriptableNodeResources: ScriptableNodeResources,
  27659. ShaderNode: ShaderNode,
  27660. TBNViewMatrix: TBNViewMatrix,
  27661. VSMShadowFilter: VSMShadowFilter,
  27662. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  27663. Var: Var,
  27664. abs: abs,
  27665. acesFilmicToneMapping: acesFilmicToneMapping,
  27666. acos: acos,
  27667. add: add,
  27668. addMethodChaining: addMethodChaining,
  27669. addNodeElement: addNodeElement,
  27670. agxToneMapping: agxToneMapping,
  27671. all: all,
  27672. alphaT: alphaT,
  27673. and: and,
  27674. anisotropy: anisotropy,
  27675. anisotropyB: anisotropyB,
  27676. anisotropyT: anisotropyT,
  27677. any: any,
  27678. append: append,
  27679. array: array,
  27680. arrayBuffer: arrayBuffer,
  27681. asin: asin,
  27682. assign: assign,
  27683. atan: atan,
  27684. atan2: atan2,
  27685. atomicAdd: atomicAdd,
  27686. atomicAnd: atomicAnd,
  27687. atomicFunc: atomicFunc,
  27688. atomicLoad: atomicLoad,
  27689. atomicMax: atomicMax,
  27690. atomicMin: atomicMin,
  27691. atomicOr: atomicOr,
  27692. atomicStore: atomicStore,
  27693. atomicSub: atomicSub,
  27694. atomicXor: atomicXor,
  27695. attenuationColor: attenuationColor,
  27696. attenuationDistance: attenuationDistance,
  27697. attribute: attribute,
  27698. attributeArray: attributeArray,
  27699. backgroundBlurriness: backgroundBlurriness,
  27700. backgroundIntensity: backgroundIntensity,
  27701. backgroundRotation: backgroundRotation,
  27702. batch: batch,
  27703. billboarding: billboarding,
  27704. bitAnd: bitAnd,
  27705. bitNot: bitNot,
  27706. bitOr: bitOr,
  27707. bitXor: bitXor,
  27708. bitangentGeometry: bitangentGeometry,
  27709. bitangentLocal: bitangentLocal,
  27710. bitangentView: bitangentView,
  27711. bitangentWorld: bitangentWorld,
  27712. bitcast: bitcast,
  27713. blendBurn: blendBurn,
  27714. blendColor: blendColor,
  27715. blendDodge: blendDodge,
  27716. blendOverlay: blendOverlay,
  27717. blendScreen: blendScreen,
  27718. blur: blur,
  27719. bool: bool,
  27720. buffer: buffer,
  27721. bufferAttribute: bufferAttribute,
  27722. bumpMap: bumpMap,
  27723. burn: burn,
  27724. bvec2: bvec2,
  27725. bvec3: bvec3,
  27726. bvec4: bvec4,
  27727. bypass: bypass,
  27728. cache: cache,
  27729. call: call,
  27730. cameraFar: cameraFar,
  27731. cameraIndex: cameraIndex,
  27732. cameraNear: cameraNear,
  27733. cameraNormalMatrix: cameraNormalMatrix,
  27734. cameraPosition: cameraPosition,
  27735. cameraProjectionMatrix: cameraProjectionMatrix,
  27736. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  27737. cameraViewMatrix: cameraViewMatrix,
  27738. cameraWorldMatrix: cameraWorldMatrix,
  27739. cbrt: cbrt,
  27740. cdl: cdl,
  27741. ceil: ceil,
  27742. checker: checker,
  27743. cineonToneMapping: cineonToneMapping,
  27744. clamp: clamp,
  27745. clearcoat: clearcoat,
  27746. clearcoatRoughness: clearcoatRoughness,
  27747. code: code,
  27748. color: color,
  27749. colorSpaceToWorking: colorSpaceToWorking,
  27750. colorToDirection: colorToDirection,
  27751. compute: compute,
  27752. cond: cond,
  27753. context: context,
  27754. convert: convert,
  27755. convertColorSpace: convertColorSpace,
  27756. convertToTexture: convertToTexture,
  27757. cos: cos,
  27758. cross: cross,
  27759. cubeTexture: cubeTexture,
  27760. dFdx: dFdx,
  27761. dFdy: dFdy,
  27762. dashSize: dashSize,
  27763. defaultBuildStages: defaultBuildStages,
  27764. defaultShaderStages: defaultShaderStages,
  27765. defined: defined,
  27766. degrees: degrees,
  27767. deltaTime: deltaTime,
  27768. densityFog: densityFog,
  27769. densityFogFactor: densityFogFactor,
  27770. depth: depth,
  27771. depthPass: depthPass,
  27772. difference: difference,
  27773. diffuseColor: diffuseColor,
  27774. directPointLight: directPointLight,
  27775. directionToColor: directionToColor,
  27776. dispersion: dispersion,
  27777. distance: distance,
  27778. div: div,
  27779. dodge: dodge,
  27780. dot: dot,
  27781. drawIndex: drawIndex,
  27782. dynamicBufferAttribute: dynamicBufferAttribute,
  27783. element: element,
  27784. emissive: emissive,
  27785. equal: equal,
  27786. equals: equals,
  27787. equirectUV: equirectUV,
  27788. exp: exp,
  27789. exp2: exp2,
  27790. expression: expression,
  27791. faceDirection: faceDirection,
  27792. faceForward: faceForward,
  27793. faceforward: faceforward,
  27794. float: float,
  27795. floor: floor,
  27796. fog: fog,
  27797. fract: fract,
  27798. frameGroup: frameGroup,
  27799. frameId: frameId,
  27800. frontFacing: frontFacing,
  27801. fwidth: fwidth,
  27802. gain: gain,
  27803. gapSize: gapSize,
  27804. getConstNodeType: getConstNodeType,
  27805. getCurrentStack: getCurrentStack,
  27806. getDirection: getDirection,
  27807. getDistanceAttenuation: getDistanceAttenuation,
  27808. getGeometryRoughness: getGeometryRoughness,
  27809. getNormalFromDepth: getNormalFromDepth,
  27810. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27811. getRoughness: getRoughness,
  27812. getScreenPosition: getScreenPosition,
  27813. getShIrradianceAt: getShIrradianceAt,
  27814. getTextureIndex: getTextureIndex,
  27815. getViewPosition: getViewPosition,
  27816. globalId: globalId,
  27817. glsl: glsl,
  27818. glslFn: glslFn,
  27819. grayscale: grayscale,
  27820. greaterThan: greaterThan,
  27821. greaterThanEqual: greaterThanEqual,
  27822. hash: hash,
  27823. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27824. highpModelViewMatrix: highpModelViewMatrix,
  27825. hue: hue,
  27826. instance: instance,
  27827. instanceIndex: instanceIndex,
  27828. instancedArray: instancedArray,
  27829. instancedBufferAttribute: instancedBufferAttribute,
  27830. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27831. instancedMesh: instancedMesh,
  27832. int: int,
  27833. inverseSqrt: inverseSqrt,
  27834. inversesqrt: inversesqrt,
  27835. invocationLocalIndex: invocationLocalIndex,
  27836. invocationSubgroupIndex: invocationSubgroupIndex,
  27837. ior: ior,
  27838. iridescence: iridescence,
  27839. iridescenceIOR: iridescenceIOR,
  27840. iridescenceThickness: iridescenceThickness,
  27841. ivec2: ivec2,
  27842. ivec3: ivec3,
  27843. ivec4: ivec4,
  27844. js: js,
  27845. label: label,
  27846. length: length,
  27847. lengthSq: lengthSq,
  27848. lessThan: lessThan,
  27849. lessThanEqual: lessThanEqual,
  27850. lightPosition: lightPosition,
  27851. lightProjectionUV: lightProjectionUV,
  27852. lightShadowMatrix: lightShadowMatrix,
  27853. lightTargetDirection: lightTargetDirection,
  27854. lightTargetPosition: lightTargetPosition,
  27855. lightViewPosition: lightViewPosition,
  27856. lightingContext: lightingContext,
  27857. lights: lights,
  27858. linearDepth: linearDepth,
  27859. linearToneMapping: linearToneMapping,
  27860. localId: localId,
  27861. log: log,
  27862. log2: log2,
  27863. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27864. loop: loop,
  27865. luminance: luminance,
  27866. mat2: mat2,
  27867. mat3: mat3,
  27868. mat4: mat4,
  27869. matcapUV: matcapUV,
  27870. materialAO: materialAO,
  27871. materialAlphaTest: materialAlphaTest,
  27872. materialAnisotropy: materialAnisotropy,
  27873. materialAnisotropyVector: materialAnisotropyVector,
  27874. materialAttenuationColor: materialAttenuationColor,
  27875. materialAttenuationDistance: materialAttenuationDistance,
  27876. materialClearcoat: materialClearcoat,
  27877. materialClearcoatNormal: materialClearcoatNormal,
  27878. materialClearcoatRoughness: materialClearcoatRoughness,
  27879. materialColor: materialColor,
  27880. materialDispersion: materialDispersion,
  27881. materialEmissive: materialEmissive,
  27882. materialIOR: materialIOR,
  27883. materialIridescence: materialIridescence,
  27884. materialIridescenceIOR: materialIridescenceIOR,
  27885. materialIridescenceThickness: materialIridescenceThickness,
  27886. materialLightMap: materialLightMap,
  27887. materialLineDashOffset: materialLineDashOffset,
  27888. materialLineDashSize: materialLineDashSize,
  27889. materialLineGapSize: materialLineGapSize,
  27890. materialLineScale: materialLineScale,
  27891. materialLineWidth: materialLineWidth,
  27892. materialMetalness: materialMetalness,
  27893. materialNormal: materialNormal,
  27894. materialOpacity: materialOpacity,
  27895. materialPointSize: materialPointSize,
  27896. materialReference: materialReference,
  27897. materialReflectivity: materialReflectivity,
  27898. materialRefractionRatio: materialRefractionRatio,
  27899. materialRotation: materialRotation,
  27900. materialRoughness: materialRoughness,
  27901. materialSheen: materialSheen,
  27902. materialSheenRoughness: materialSheenRoughness,
  27903. materialShininess: materialShininess,
  27904. materialSpecular: materialSpecular,
  27905. materialSpecularColor: materialSpecularColor,
  27906. materialSpecularIntensity: materialSpecularIntensity,
  27907. materialSpecularStrength: materialSpecularStrength,
  27908. materialThickness: materialThickness,
  27909. materialTransmission: materialTransmission,
  27910. max: max$1,
  27911. maxMipLevel: maxMipLevel,
  27912. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27913. metalness: metalness,
  27914. min: min$1,
  27915. mix: mix,
  27916. mixElement: mixElement,
  27917. mod: mod,
  27918. modInt: modInt,
  27919. modelDirection: modelDirection,
  27920. modelNormalMatrix: modelNormalMatrix,
  27921. modelPosition: modelPosition,
  27922. modelScale: modelScale,
  27923. modelViewMatrix: modelViewMatrix,
  27924. modelViewPosition: modelViewPosition,
  27925. modelViewProjection: modelViewProjection,
  27926. modelWorldMatrix: modelWorldMatrix,
  27927. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27928. morphReference: morphReference,
  27929. mrt: mrt,
  27930. mul: mul,
  27931. mx_aastep: mx_aastep,
  27932. mx_cell_noise_float: mx_cell_noise_float,
  27933. mx_contrast: mx_contrast,
  27934. mx_fractal_noise_float: mx_fractal_noise_float,
  27935. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27936. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27937. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27938. mx_hsvtorgb: mx_hsvtorgb,
  27939. mx_noise_float: mx_noise_float,
  27940. mx_noise_vec3: mx_noise_vec3,
  27941. mx_noise_vec4: mx_noise_vec4,
  27942. mx_ramplr: mx_ramplr,
  27943. mx_ramptb: mx_ramptb,
  27944. mx_rgbtohsv: mx_rgbtohsv,
  27945. mx_safepower: mx_safepower,
  27946. mx_splitlr: mx_splitlr,
  27947. mx_splittb: mx_splittb,
  27948. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27949. mx_transform_uv: mx_transform_uv,
  27950. mx_worley_noise_float: mx_worley_noise_float,
  27951. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27952. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27953. negate: negate,
  27954. neutralToneMapping: neutralToneMapping,
  27955. nodeArray: nodeArray,
  27956. nodeImmutable: nodeImmutable,
  27957. nodeObject: nodeObject,
  27958. nodeObjects: nodeObjects,
  27959. nodeProxy: nodeProxy,
  27960. normalFlat: normalFlat,
  27961. normalGeometry: normalGeometry,
  27962. normalLocal: normalLocal,
  27963. normalMap: normalMap,
  27964. normalView: normalView,
  27965. normalWorld: normalWorld,
  27966. normalize: normalize,
  27967. not: not,
  27968. notEqual: notEqual,
  27969. numWorkgroups: numWorkgroups,
  27970. objectDirection: objectDirection,
  27971. objectGroup: objectGroup,
  27972. objectPosition: objectPosition,
  27973. objectScale: objectScale,
  27974. objectViewPosition: objectViewPosition,
  27975. objectWorldMatrix: objectWorldMatrix,
  27976. oneMinus: oneMinus,
  27977. or: or,
  27978. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27979. oscSawtooth: oscSawtooth,
  27980. oscSine: oscSine,
  27981. oscSquare: oscSquare,
  27982. oscTriangle: oscTriangle,
  27983. output: output,
  27984. outputStruct: outputStruct,
  27985. overlay: overlay,
  27986. overloadingFn: overloadingFn,
  27987. parabola: parabola,
  27988. parallaxDirection: parallaxDirection,
  27989. parallaxUV: parallaxUV,
  27990. parameter: parameter,
  27991. pass: pass,
  27992. passTexture: passTexture,
  27993. pcurve: pcurve,
  27994. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27995. pmremTexture: pmremTexture,
  27996. pointUV: pointUV,
  27997. pointWidth: pointWidth,
  27998. positionGeometry: positionGeometry,
  27999. positionLocal: positionLocal,
  28000. positionPrevious: positionPrevious,
  28001. positionView: positionView,
  28002. positionViewDirection: positionViewDirection,
  28003. positionWorld: positionWorld,
  28004. positionWorldDirection: positionWorldDirection,
  28005. posterize: posterize,
  28006. pow: pow,
  28007. pow2: pow2,
  28008. pow3: pow3,
  28009. pow4: pow4,
  28010. property: property,
  28011. radians: radians,
  28012. rand: rand,
  28013. range: range,
  28014. rangeFog: rangeFog,
  28015. rangeFogFactor: rangeFogFactor,
  28016. reciprocal: reciprocal,
  28017. reference: reference,
  28018. referenceBuffer: referenceBuffer,
  28019. reflect: reflect,
  28020. reflectVector: reflectVector,
  28021. reflectView: reflectView,
  28022. reflector: reflector,
  28023. refract: refract,
  28024. refractVector: refractVector,
  28025. refractView: refractView,
  28026. reinhardToneMapping: reinhardToneMapping,
  28027. remainder: remainder,
  28028. remap: remap,
  28029. remapClamp: remapClamp,
  28030. renderGroup: renderGroup,
  28031. renderOutput: renderOutput,
  28032. rendererReference: rendererReference,
  28033. rotate: rotate,
  28034. rotateUV: rotateUV,
  28035. roughness: roughness,
  28036. round: round,
  28037. rtt: rtt,
  28038. sRGBTransferEOTF: sRGBTransferEOTF,
  28039. sRGBTransferOETF: sRGBTransferOETF,
  28040. sampler: sampler,
  28041. saturate: saturate,
  28042. saturation: saturation,
  28043. screen: screen,
  28044. screenCoordinate: screenCoordinate,
  28045. screenSize: screenSize,
  28046. screenUV: screenUV,
  28047. scriptable: scriptable,
  28048. scriptableValue: scriptableValue,
  28049. select: select,
  28050. setCurrentStack: setCurrentStack,
  28051. shaderStages: shaderStages,
  28052. shadow: shadow,
  28053. shadowPositionWorld: shadowPositionWorld,
  28054. shapeCircle: shapeCircle,
  28055. sharedUniformGroup: sharedUniformGroup,
  28056. sheen: sheen,
  28057. sheenRoughness: sheenRoughness,
  28058. shiftLeft: shiftLeft,
  28059. shiftRight: shiftRight,
  28060. shininess: shininess,
  28061. sign: sign,
  28062. sin: sin,
  28063. sinc: sinc,
  28064. skinning: skinning,
  28065. skinningReference: skinningReference,
  28066. smoothstep: smoothstep,
  28067. smoothstepElement: smoothstepElement,
  28068. specularColor: specularColor,
  28069. specularF90: specularF90,
  28070. spherizeUV: spherizeUV,
  28071. split: split,
  28072. spritesheetUV: spritesheetUV,
  28073. sqrt: sqrt,
  28074. stack: stack,
  28075. step: step,
  28076. storage: storage,
  28077. storageBarrier: storageBarrier,
  28078. storageObject: storageObject,
  28079. storageTexture: storageTexture,
  28080. string: string,
  28081. struct: struct,
  28082. sub: sub,
  28083. subgroupIndex: subgroupIndex,
  28084. subgroupSize: subgroupSize,
  28085. tan: tan,
  28086. tangentGeometry: tangentGeometry,
  28087. tangentLocal: tangentLocal,
  28088. tangentView: tangentView,
  28089. tangentWorld: tangentWorld,
  28090. temp: temp,
  28091. texture: texture,
  28092. texture3D: texture3D,
  28093. textureBarrier: textureBarrier,
  28094. textureBicubic: textureBicubic,
  28095. textureCubeUV: textureCubeUV,
  28096. textureLoad: textureLoad,
  28097. textureSize: textureSize,
  28098. textureStore: textureStore,
  28099. thickness: thickness,
  28100. time: time,
  28101. timerDelta: timerDelta,
  28102. timerGlobal: timerGlobal,
  28103. timerLocal: timerLocal,
  28104. toOutputColorSpace: toOutputColorSpace,
  28105. toWorkingColorSpace: toWorkingColorSpace,
  28106. toneMapping: toneMapping,
  28107. toneMappingExposure: toneMappingExposure,
  28108. toonOutlinePass: toonOutlinePass,
  28109. transformDirection: transformDirection,
  28110. transformNormal: transformNormal,
  28111. transformNormalToView: transformNormalToView,
  28112. transformedBentNormalView: transformedBentNormalView,
  28113. transformedBitangentView: transformedBitangentView,
  28114. transformedBitangentWorld: transformedBitangentWorld,
  28115. transformedClearcoatNormalView: transformedClearcoatNormalView,
  28116. transformedNormalView: transformedNormalView,
  28117. transformedNormalWorld: transformedNormalWorld,
  28118. transformedTangentView: transformedTangentView,
  28119. transformedTangentWorld: transformedTangentWorld,
  28120. transmission: transmission,
  28121. transpose: transpose,
  28122. triNoise3D: triNoise3D,
  28123. triplanarTexture: triplanarTexture,
  28124. triplanarTextures: triplanarTextures,
  28125. trunc: trunc,
  28126. tslFn: tslFn,
  28127. uint: uint,
  28128. uniform: uniform,
  28129. uniformArray: uniformArray,
  28130. uniformGroup: uniformGroup,
  28131. uniforms: uniforms,
  28132. userData: userData,
  28133. uv: uv,
  28134. uvec2: uvec2,
  28135. uvec3: uvec3,
  28136. uvec4: uvec4,
  28137. varying: varying,
  28138. varyingProperty: varyingProperty,
  28139. vec2: vec2,
  28140. vec3: vec3,
  28141. vec4: vec4,
  28142. vectorComponents: vectorComponents,
  28143. velocity: velocity,
  28144. vertexColor: vertexColor,
  28145. vertexIndex: vertexIndex,
  28146. vertexStage: vertexStage,
  28147. vibrance: vibrance,
  28148. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  28149. viewZToOrthographicDepth: viewZToOrthographicDepth,
  28150. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  28151. viewport: viewport,
  28152. viewportBottomLeft: viewportBottomLeft,
  28153. viewportCoordinate: viewportCoordinate,
  28154. viewportDepthTexture: viewportDepthTexture,
  28155. viewportLinearDepth: viewportLinearDepth,
  28156. viewportMipTexture: viewportMipTexture,
  28157. viewportResolution: viewportResolution,
  28158. viewportSafeUV: viewportSafeUV,
  28159. viewportSharedTexture: viewportSharedTexture,
  28160. viewportSize: viewportSize,
  28161. viewportTexture: viewportTexture,
  28162. viewportTopLeft: viewportTopLeft,
  28163. viewportUV: viewportUV,
  28164. wgsl: wgsl,
  28165. wgslFn: wgslFn,
  28166. workgroupArray: workgroupArray,
  28167. workgroupBarrier: workgroupBarrier,
  28168. workgroupId: workgroupId,
  28169. workingToColorSpace: workingToColorSpace,
  28170. xor: xor
  28171. });
  28172. const _clearColor$1 = /*@__PURE__*/ new Color4();
  28173. /**
  28174. * This renderer module manages the background.
  28175. *
  28176. * @private
  28177. * @augments DataMap
  28178. */
  28179. class Background extends DataMap {
  28180. /**
  28181. * Constructs a new background management component.
  28182. *
  28183. * @param {Renderer} renderer - The renderer.
  28184. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  28185. */
  28186. constructor( renderer, nodes ) {
  28187. super();
  28188. /**
  28189. * The renderer.
  28190. *
  28191. * @type {Renderer}
  28192. */
  28193. this.renderer = renderer;
  28194. /**
  28195. * Renderer component for managing nodes related logic.
  28196. *
  28197. * @type {Nodes}
  28198. */
  28199. this.nodes = nodes;
  28200. }
  28201. /**
  28202. * Updates the background for the given scene. Depending on how `Scene.background`
  28203. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  28204. * or add a mesh to the render list for rendering the background as a textured plane
  28205. * or skybox.
  28206. *
  28207. * @param {Scene} scene - The scene.
  28208. * @param {RenderList} renderList - The current render list.
  28209. * @param {RenderContext} renderContext - The current render context.
  28210. */
  28211. update( scene, renderList, renderContext ) {
  28212. const renderer = this.renderer;
  28213. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  28214. let forceClear = false;
  28215. if ( background === null ) {
  28216. // no background settings, use clear color configuration from the renderer
  28217. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  28218. _clearColor$1.a = renderer._clearColor.a;
  28219. } else if ( background.isColor === true ) {
  28220. // background is an opaque color
  28221. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  28222. _clearColor$1.a = 1;
  28223. forceClear = true;
  28224. } else if ( background.isNode === true ) {
  28225. const sceneData = this.get( scene );
  28226. const backgroundNode = background;
  28227. _clearColor$1.copy( renderer._clearColor );
  28228. let backgroundMesh = sceneData.backgroundMesh;
  28229. if ( backgroundMesh === undefined ) {
  28230. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  28231. // @TODO: Add Texture2D support using node context
  28232. getUV: () => backgroundRotation.mul( normalWorld ),
  28233. getTextureLevel: () => backgroundBlurriness
  28234. } );
  28235. let viewProj = modelViewProjection;
  28236. viewProj = viewProj.setZ( viewProj.w );
  28237. const nodeMaterial = new NodeMaterial();
  28238. nodeMaterial.name = 'Background.material';
  28239. nodeMaterial.side = BackSide;
  28240. nodeMaterial.depthTest = false;
  28241. nodeMaterial.depthWrite = false;
  28242. nodeMaterial.fog = false;
  28243. nodeMaterial.lights = false;
  28244. nodeMaterial.vertexNode = viewProj;
  28245. nodeMaterial.colorNode = backgroundMeshNode;
  28246. sceneData.backgroundMeshNode = backgroundMeshNode;
  28247. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  28248. backgroundMesh.frustumCulled = false;
  28249. backgroundMesh.name = 'Background.mesh';
  28250. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  28251. this.matrixWorld.copyPosition( camera.matrixWorld );
  28252. };
  28253. }
  28254. const backgroundCacheKey = backgroundNode.getCacheKey();
  28255. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  28256. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  28257. sceneData.backgroundMeshNode.needsUpdate = true;
  28258. backgroundMesh.material.needsUpdate = true;
  28259. sceneData.backgroundCacheKey = backgroundCacheKey;
  28260. }
  28261. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  28262. } else {
  28263. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  28264. }
  28265. //
  28266. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  28267. if ( environmentBlendMode === 'additive' ) {
  28268. _clearColor$1.set( 0, 0, 0, 1 );
  28269. } else if ( environmentBlendMode === 'alpha-blend' ) {
  28270. _clearColor$1.set( 0, 0, 0, 0 );
  28271. }
  28272. //
  28273. if ( renderer.autoClear === true || forceClear === true ) {
  28274. const clearColorValue = renderContext.clearColorValue;
  28275. clearColorValue.r = _clearColor$1.r;
  28276. clearColorValue.g = _clearColor$1.g;
  28277. clearColorValue.b = _clearColor$1.b;
  28278. clearColorValue.a = _clearColor$1.a;
  28279. // premultiply alpha
  28280. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  28281. clearColorValue.r *= clearColorValue.a;
  28282. clearColorValue.g *= clearColorValue.a;
  28283. clearColorValue.b *= clearColorValue.a;
  28284. }
  28285. //
  28286. renderContext.depthClearValue = renderer._clearDepth;
  28287. renderContext.stencilClearValue = renderer._clearStencil;
  28288. renderContext.clearColor = renderer.autoClearColor === true;
  28289. renderContext.clearDepth = renderer.autoClearDepth === true;
  28290. renderContext.clearStencil = renderer.autoClearStencil === true;
  28291. } else {
  28292. renderContext.clearColor = false;
  28293. renderContext.clearDepth = false;
  28294. renderContext.clearStencil = false;
  28295. }
  28296. }
  28297. }
  28298. let _id$6 = 0;
  28299. /**
  28300. * A bind group represents a collection of bindings and thus a collection
  28301. * or resources. Bind groups are assigned to pipelines to provide them
  28302. * with the required resources (like uniform buffers or textures).
  28303. *
  28304. * @private
  28305. */
  28306. class BindGroup {
  28307. /**
  28308. * Constructs a new bind group.
  28309. *
  28310. * @param {String} name - The bind group's name.
  28311. * @param {Array<Binding>} bindings - An array of bindings.
  28312. * @param {Number} index - The group index.
  28313. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  28314. */
  28315. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  28316. /**
  28317. * The bind group's name.
  28318. *
  28319. * @type {String}
  28320. */
  28321. this.name = name;
  28322. /**
  28323. * An array of bindings.
  28324. *
  28325. * @type {Array<Binding>}
  28326. */
  28327. this.bindings = bindings;
  28328. /**
  28329. * The group index.
  28330. *
  28331. * @type {Number}
  28332. */
  28333. this.index = index;
  28334. /**
  28335. * An array of reference bindings.
  28336. *
  28337. * @type {Array<Binding>}
  28338. */
  28339. this.bindingsReference = bindingsReference;
  28340. /**
  28341. * The group's ID.
  28342. *
  28343. * @type {Number}
  28344. */
  28345. this.id = _id$6 ++;
  28346. }
  28347. }
  28348. /**
  28349. * This module represents the state of a node builder after it was
  28350. * used to build the nodes for a render object. The state holds the
  28351. * results of the build for further processing in the renderer.
  28352. *
  28353. * Render objects with identical cache keys share the same node builder state.
  28354. *
  28355. * @private
  28356. */
  28357. class NodeBuilderState {
  28358. /**
  28359. * Constructs a new node builder state.
  28360. *
  28361. * @param {String?} vertexShader - The native vertex shader code.
  28362. * @param {String?} fragmentShader - The native fragment shader code.
  28363. * @param {String?} computeShader - The native compute shader code.
  28364. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  28365. * @param {Array<BindGroup>} bindings - An array of bind groups.
  28366. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  28367. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  28368. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  28369. * @param {NodeMaterialObserver} observer - A node material observer.
  28370. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  28371. */
  28372. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  28373. /**
  28374. * The native vertex shader code.
  28375. *
  28376. * @type {String}
  28377. */
  28378. this.vertexShader = vertexShader;
  28379. /**
  28380. * The native fragment shader code.
  28381. *
  28382. * @type {String}
  28383. */
  28384. this.fragmentShader = fragmentShader;
  28385. /**
  28386. * The native compute shader code.
  28387. *
  28388. * @type {String}
  28389. */
  28390. this.computeShader = computeShader;
  28391. /**
  28392. * An array with transform attribute objects.
  28393. * Only relevant when using compute shaders with WebGL 2.
  28394. *
  28395. * @type {Array<Object>}
  28396. */
  28397. this.transforms = transforms;
  28398. /**
  28399. * An array of node attributes representing
  28400. * the attributes of the shaders.
  28401. *
  28402. * @type {Array<NodeAttribute>}
  28403. */
  28404. this.nodeAttributes = nodeAttributes;
  28405. /**
  28406. * An array of bind groups representing the uniform or storage
  28407. * buffers, texture or samplers of the shader.
  28408. *
  28409. * @type {Array<BindGroup>}
  28410. */
  28411. this.bindings = bindings;
  28412. /**
  28413. * An array of nodes that implement their `update()` method.
  28414. *
  28415. * @type {Array<Node>}
  28416. */
  28417. this.updateNodes = updateNodes;
  28418. /**
  28419. * An array of nodes that implement their `updateBefore()` method.
  28420. *
  28421. * @type {Array<Node>}
  28422. */
  28423. this.updateBeforeNodes = updateBeforeNodes;
  28424. /**
  28425. * An array of nodes that implement their `updateAfter()` method.
  28426. *
  28427. * @type {Array<Node>}
  28428. */
  28429. this.updateAfterNodes = updateAfterNodes;
  28430. /**
  28431. * A node material observer.
  28432. *
  28433. * @type {NodeMaterialObserver}
  28434. */
  28435. this.observer = observer;
  28436. /**
  28437. * How often this state is used by render objects.
  28438. *
  28439. * @type {Number}
  28440. */
  28441. this.usedTimes = 0;
  28442. }
  28443. /**
  28444. * This method is used to create a array of bind groups based
  28445. * on the existing bind groups of this state. Shared groups are
  28446. * not cloned.
  28447. *
  28448. * @return {Array<BindGroup>} A array of bind groups.
  28449. */
  28450. createBindings() {
  28451. const bindings = [];
  28452. for ( const instanceGroup of this.bindings ) {
  28453. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  28454. if ( shared !== true ) {
  28455. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  28456. bindings.push( bindingsGroup );
  28457. for ( const instanceBinding of instanceGroup.bindings ) {
  28458. bindingsGroup.bindings.push( instanceBinding.clone() );
  28459. }
  28460. } else {
  28461. bindings.push( instanceGroup );
  28462. }
  28463. }
  28464. return bindings;
  28465. }
  28466. }
  28467. /**
  28468. * {@link NodeBuilder} is going to create instances of this class during the build process
  28469. * of nodes. They represent the final shader attributes that are going to be generated
  28470. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  28471. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  28472. */
  28473. class NodeAttribute {
  28474. /**
  28475. * Constructs a new node attribute.
  28476. *
  28477. * @param {String} name - The name of the attribute.
  28478. * @param {String} type - The type of the attribute.
  28479. * @param {Node?} node - An optional reference to the node.
  28480. */
  28481. constructor( name, type, node = null ) {
  28482. /**
  28483. * This flag can be used for type testing.
  28484. *
  28485. * @type {Boolean}
  28486. * @readonly
  28487. * @default true
  28488. */
  28489. this.isNodeAttribute = true;
  28490. /**
  28491. * The name of the attribute.
  28492. *
  28493. * @type {String}
  28494. */
  28495. this.name = name;
  28496. /**
  28497. * The type of the attribute.
  28498. *
  28499. * @type {String}
  28500. */
  28501. this.type = type;
  28502. /**
  28503. * An optional reference to the node.
  28504. *
  28505. * @type {Node?}
  28506. * @default null
  28507. */
  28508. this.node = node;
  28509. }
  28510. }
  28511. /**
  28512. * {@link NodeBuilder} is going to create instances of this class during the build process
  28513. * of nodes. They represent the final shader uniforms that are going to be generated
  28514. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  28515. * for this purpose.
  28516. */
  28517. class NodeUniform {
  28518. /**
  28519. * Constructs a new node uniform.
  28520. *
  28521. * @param {String} name - The name of the uniform.
  28522. * @param {String} type - The type of the uniform.
  28523. * @param {UniformNode} node - An reference to the node.
  28524. */
  28525. constructor( name, type, node ) {
  28526. /**
  28527. * This flag can be used for type testing.
  28528. *
  28529. * @type {Boolean}
  28530. * @readonly
  28531. * @default true
  28532. */
  28533. this.isNodeUniform = true;
  28534. /**
  28535. * The name of the uniform.
  28536. *
  28537. * @type {String}
  28538. */
  28539. this.name = name;
  28540. /**
  28541. * The type of the uniform.
  28542. *
  28543. * @type {String}
  28544. */
  28545. this.type = type;
  28546. /**
  28547. * An reference to the node.
  28548. *
  28549. * @type {UniformNode}
  28550. */
  28551. this.node = node.getSelf();
  28552. }
  28553. /**
  28554. * The value of the uniform node.
  28555. *
  28556. * @type {Any}
  28557. */
  28558. get value() {
  28559. return this.node.value;
  28560. }
  28561. set value( val ) {
  28562. this.node.value = val;
  28563. }
  28564. /**
  28565. * The id of the uniform node.
  28566. *
  28567. * @type {Number}
  28568. */
  28569. get id() {
  28570. return this.node.id;
  28571. }
  28572. /**
  28573. * The uniform node's group.
  28574. *
  28575. * @type {UniformGroupNode}
  28576. */
  28577. get groupNode() {
  28578. return this.node.groupNode;
  28579. }
  28580. }
  28581. /**
  28582. * {@link NodeBuilder} is going to create instances of this class during the build process
  28583. * of nodes. They represent the final shader variables that are going to be generated
  28584. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  28585. * this purpose.
  28586. */
  28587. class NodeVar {
  28588. /**
  28589. * Constructs a new node variable.
  28590. *
  28591. * @param {String} name - The name of the variable.
  28592. * @param {String} type - The type of the variable.
  28593. * @param {Boolean} [readOnly=false] - The read-only flag.
  28594. * @param {Number?} [count=null] - The size.
  28595. */
  28596. constructor( name, type, readOnly = false, count = null ) {
  28597. /**
  28598. * This flag can be used for type testing.
  28599. *
  28600. * @type {Boolean}
  28601. * @readonly
  28602. * @default true
  28603. */
  28604. this.isNodeVar = true;
  28605. /**
  28606. * The name of the variable.
  28607. *
  28608. * @type {String}
  28609. */
  28610. this.name = name;
  28611. /**
  28612. * The type of the variable.
  28613. *
  28614. * @type {String}
  28615. */
  28616. this.type = type;
  28617. /**
  28618. * The read-only flag.
  28619. *
  28620. * @type {Boolean}
  28621. */
  28622. this.readOnly = readOnly;
  28623. /**
  28624. * The size.
  28625. *
  28626. * @type {Number?}
  28627. */
  28628. this.count = count;
  28629. }
  28630. }
  28631. /**
  28632. * {@link NodeBuilder} is going to create instances of this class during the build process
  28633. * of nodes. They represent the final shader varyings that are going to be generated
  28634. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  28635. * this purpose.
  28636. *
  28637. * @augments NodeVar
  28638. */
  28639. class NodeVarying extends NodeVar {
  28640. /**
  28641. * Constructs a new node varying.
  28642. *
  28643. * @param {String} name - The name of the varying.
  28644. * @param {String} type - The type of the varying.
  28645. */
  28646. constructor( name, type ) {
  28647. super( name, type );
  28648. /**
  28649. * Whether this varying requires interpolation or not. This property can be used
  28650. * to check if the varying can be optimized for a variable.
  28651. *
  28652. * @type {Boolean}
  28653. * @default false
  28654. */
  28655. this.needsInterpolation = false;
  28656. /**
  28657. * This flag can be used for type testing.
  28658. *
  28659. * @type {Boolean}
  28660. * @readonly
  28661. * @default true
  28662. */
  28663. this.isNodeVarying = true;
  28664. }
  28665. }
  28666. /**
  28667. * {@link NodeBuilder} is going to create instances of this class during the build process
  28668. * of nodes. They represent user-defined, native shader code portions that are going to be
  28669. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  28670. * for this purpose.
  28671. */
  28672. class NodeCode {
  28673. /**
  28674. * Constructs a new code node.
  28675. *
  28676. * @param {String} name - The name of the code.
  28677. * @param {String} type - The node type.
  28678. * @param {String} [code=''] - The native shader code.
  28679. */
  28680. constructor( name, type, code = '' ) {
  28681. /**
  28682. * The name of the code.
  28683. *
  28684. * @type {String}
  28685. */
  28686. this.name = name;
  28687. /**
  28688. * The node type.
  28689. *
  28690. * @type {String}
  28691. */
  28692. this.type = type;
  28693. /**
  28694. * The native shader code.
  28695. *
  28696. * @type {String}
  28697. * @default ''
  28698. */
  28699. this.code = code;
  28700. Object.defineProperty( this, 'isNodeCode', { value: true } );
  28701. }
  28702. }
  28703. let _id$5 = 0;
  28704. /**
  28705. * This utility class is used in {@link NodeBuilder} as an internal
  28706. * cache data structure for node data.
  28707. */
  28708. class NodeCache {
  28709. /**
  28710. * Constructs a new node cache.
  28711. *
  28712. * @param {NodeCache?} parent - A reference to a parent cache.
  28713. */
  28714. constructor( parent = null ) {
  28715. /**
  28716. * The id of the cache.
  28717. *
  28718. * @type {Number}
  28719. * @readonly
  28720. */
  28721. this.id = _id$5 ++;
  28722. /**
  28723. * A weak map for managing node data.
  28724. *
  28725. * @type {WeakMap<Node, Object>}
  28726. */
  28727. this.nodesData = new WeakMap();
  28728. /**
  28729. * Reference to a parent node cache.
  28730. *
  28731. * @type {NodeCache?}
  28732. * @default null
  28733. */
  28734. this.parent = parent;
  28735. }
  28736. /**
  28737. * Returns the data for the given node.
  28738. *
  28739. * @param {Node} node - The node.
  28740. * @return {Object?} The data for the node.
  28741. */
  28742. getData( node ) {
  28743. let data = this.nodesData.get( node );
  28744. if ( data === undefined && this.parent !== null ) {
  28745. data = this.parent.getData( node );
  28746. }
  28747. return data;
  28748. }
  28749. /**
  28750. * Sets the data for a given node.
  28751. *
  28752. * @param {Node} node - The node.
  28753. * @param {Object} data - The data that should be cached.
  28754. */
  28755. setData( node, data ) {
  28756. this.nodesData.set( node, data );
  28757. }
  28758. }
  28759. class StructType {
  28760. constructor( name, members ) {
  28761. this.name = name;
  28762. this.members = members;
  28763. this.output = false;
  28764. }
  28765. }
  28766. /**
  28767. * Abstract base class for uniforms.
  28768. *
  28769. * @abstract
  28770. * @private
  28771. */
  28772. class Uniform {
  28773. /**
  28774. * Constructs a new uniform.
  28775. *
  28776. * @param {String} name - The uniform's name.
  28777. * @param {Any} value - The uniform's value.
  28778. */
  28779. constructor( name, value ) {
  28780. /**
  28781. * The uniform's name.
  28782. *
  28783. * @type {String}
  28784. */
  28785. this.name = name;
  28786. /**
  28787. * The uniform's value.
  28788. *
  28789. * @type {Any}
  28790. */
  28791. this.value = value;
  28792. /**
  28793. * Used to build the uniform buffer according to the STD140 layout.
  28794. * Derived uniforms will set this property to a data type specific
  28795. * value.
  28796. *
  28797. * @type {Number}
  28798. */
  28799. this.boundary = 0;
  28800. /**
  28801. * The item size. Derived uniforms will set this property to a data
  28802. * type specific value.
  28803. *
  28804. * @type {Number}
  28805. */
  28806. this.itemSize = 0;
  28807. /**
  28808. * This property is set by {@link UniformsGroup} and marks
  28809. * the start position in the uniform buffer.
  28810. *
  28811. * @type {Number}
  28812. */
  28813. this.offset = 0;
  28814. }
  28815. /**
  28816. * Sets the uniform's value.
  28817. *
  28818. * @param {Any} value - The value to set.
  28819. */
  28820. setValue( value ) {
  28821. this.value = value;
  28822. }
  28823. /**
  28824. * Returns the uniform's value.
  28825. *
  28826. * @return {Any} The value.
  28827. */
  28828. getValue() {
  28829. return this.value;
  28830. }
  28831. }
  28832. /**
  28833. * Represents a Number uniform.
  28834. *
  28835. * @private
  28836. * @augments Uniform
  28837. */
  28838. class NumberUniform extends Uniform {
  28839. /**
  28840. * Constructs a new Number uniform.
  28841. *
  28842. * @param {String} name - The uniform's name.
  28843. * @param {Number} value - The uniform's value.
  28844. */
  28845. constructor( name, value = 0 ) {
  28846. super( name, value );
  28847. /**
  28848. * This flag can be used for type testing.
  28849. *
  28850. * @type {Boolean}
  28851. * @readonly
  28852. * @default true
  28853. */
  28854. this.isNumberUniform = true;
  28855. this.boundary = 4;
  28856. this.itemSize = 1;
  28857. }
  28858. }
  28859. /**
  28860. * Represents a Vector2 uniform.
  28861. *
  28862. * @private
  28863. * @augments Uniform
  28864. */
  28865. class Vector2Uniform extends Uniform {
  28866. /**
  28867. * Constructs a new Number uniform.
  28868. *
  28869. * @param {String} name - The uniform's name.
  28870. * @param {Vector2} value - The uniform's value.
  28871. */
  28872. constructor( name, value = new Vector2() ) {
  28873. super( name, value );
  28874. /**
  28875. * This flag can be used for type testing.
  28876. *
  28877. * @type {Boolean}
  28878. * @readonly
  28879. * @default true
  28880. */
  28881. this.isVector2Uniform = true;
  28882. this.boundary = 8;
  28883. this.itemSize = 2;
  28884. }
  28885. }
  28886. /**
  28887. * Represents a Vector3 uniform.
  28888. *
  28889. * @private
  28890. * @augments Uniform
  28891. */
  28892. class Vector3Uniform extends Uniform {
  28893. /**
  28894. * Constructs a new Number uniform.
  28895. *
  28896. * @param {String} name - The uniform's name.
  28897. * @param {Vector3} value - The uniform's value.
  28898. */
  28899. constructor( name, value = new Vector3() ) {
  28900. super( name, value );
  28901. /**
  28902. * This flag can be used for type testing.
  28903. *
  28904. * @type {Boolean}
  28905. * @readonly
  28906. * @default true
  28907. */
  28908. this.isVector3Uniform = true;
  28909. this.boundary = 16;
  28910. this.itemSize = 3;
  28911. }
  28912. }
  28913. /**
  28914. * Represents a Vector4 uniform.
  28915. *
  28916. * @private
  28917. * @augments Uniform
  28918. */
  28919. class Vector4Uniform extends Uniform {
  28920. /**
  28921. * Constructs a new Number uniform.
  28922. *
  28923. * @param {String} name - The uniform's name.
  28924. * @param {Vector4} value - The uniform's value.
  28925. */
  28926. constructor( name, value = new Vector4() ) {
  28927. super( name, value );
  28928. /**
  28929. * This flag can be used for type testing.
  28930. *
  28931. * @type {Boolean}
  28932. * @readonly
  28933. * @default true
  28934. */
  28935. this.isVector4Uniform = true;
  28936. this.boundary = 16;
  28937. this.itemSize = 4;
  28938. }
  28939. }
  28940. /**
  28941. * Represents a Color uniform.
  28942. *
  28943. * @private
  28944. * @augments Uniform
  28945. */
  28946. class ColorUniform extends Uniform {
  28947. /**
  28948. * Constructs a new Number uniform.
  28949. *
  28950. * @param {String} name - The uniform's name.
  28951. * @param {Color} value - The uniform's value.
  28952. */
  28953. constructor( name, value = new Color() ) {
  28954. super( name, value );
  28955. /**
  28956. * This flag can be used for type testing.
  28957. *
  28958. * @type {Boolean}
  28959. * @readonly
  28960. * @default true
  28961. */
  28962. this.isColorUniform = true;
  28963. this.boundary = 16;
  28964. this.itemSize = 3;
  28965. }
  28966. }
  28967. /**
  28968. * Represents a Matrix2 uniform.
  28969. *
  28970. * @private
  28971. * @augments Uniform
  28972. */
  28973. class Matrix2Uniform extends Uniform {
  28974. /**
  28975. * Constructs a new Number uniform.
  28976. *
  28977. * @param {String} name - The uniform's name.
  28978. * @param {Matrix2} value - The uniform's value.
  28979. */
  28980. constructor( name, value = new Matrix2() ) {
  28981. super( name, value );
  28982. /**
  28983. * This flag can be used for type testing.
  28984. *
  28985. * @type {Boolean}
  28986. * @readonly
  28987. * @default true
  28988. */
  28989. this.isMatrix2Uniform = true;
  28990. this.boundary = 16;
  28991. this.itemSize = 4;
  28992. }
  28993. }
  28994. /**
  28995. * Represents a Matrix3 uniform.
  28996. *
  28997. * @private
  28998. * @augments Uniform
  28999. */
  29000. class Matrix3Uniform extends Uniform {
  29001. /**
  29002. * Constructs a new Number uniform.
  29003. *
  29004. * @param {String} name - The uniform's name.
  29005. * @param {Matrix3} value - The uniform's value.
  29006. */
  29007. constructor( name, value = new Matrix3() ) {
  29008. super( name, value );
  29009. /**
  29010. * This flag can be used for type testing.
  29011. *
  29012. * @type {Boolean}
  29013. * @readonly
  29014. * @default true
  29015. */
  29016. this.isMatrix3Uniform = true;
  29017. this.boundary = 48;
  29018. this.itemSize = 12;
  29019. }
  29020. }
  29021. /**
  29022. * Represents a Matrix4 uniform.
  29023. *
  29024. * @private
  29025. * @augments Uniform
  29026. */
  29027. class Matrix4Uniform extends Uniform {
  29028. /**
  29029. * Constructs a new Number uniform.
  29030. *
  29031. * @param {String} name - The uniform's name.
  29032. * @param {Matrix4} value - The uniform's value.
  29033. */
  29034. constructor( name, value = new Matrix4() ) {
  29035. super( name, value );
  29036. /**
  29037. * This flag can be used for type testing.
  29038. *
  29039. * @type {Boolean}
  29040. * @readonly
  29041. * @default true
  29042. */
  29043. this.isMatrix4Uniform = true;
  29044. this.boundary = 64;
  29045. this.itemSize = 16;
  29046. }
  29047. }
  29048. /**
  29049. * A special form of Number uniform binding type.
  29050. * It's value is managed by a node object.
  29051. *
  29052. * @private
  29053. * @augments NumberUniform
  29054. */
  29055. class NumberNodeUniform extends NumberUniform {
  29056. /**
  29057. * Constructs a new node-based Number uniform.
  29058. *
  29059. * @param {NodeUniform} nodeUniform - The node uniform.
  29060. */
  29061. constructor( nodeUniform ) {
  29062. super( nodeUniform.name, nodeUniform.value );
  29063. /**
  29064. * The node uniform.
  29065. *
  29066. * @type {NodeUniform}
  29067. */
  29068. this.nodeUniform = nodeUniform;
  29069. }
  29070. /**
  29071. * Overwritten to return the value of the node uniform.
  29072. *
  29073. * @return {Number} The value.
  29074. */
  29075. getValue() {
  29076. return this.nodeUniform.value;
  29077. }
  29078. /**
  29079. * Returns the node uniform data type.
  29080. *
  29081. * @return {String} The data type.
  29082. */
  29083. getType() {
  29084. return this.nodeUniform.type;
  29085. }
  29086. }
  29087. /**
  29088. * A special form of Vector2 uniform binding type.
  29089. * It's value is managed by a node object.
  29090. *
  29091. * @private
  29092. * @augments Vector2Uniform
  29093. */
  29094. class Vector2NodeUniform extends Vector2Uniform {
  29095. /**
  29096. * Constructs a new node-based Vector2 uniform.
  29097. *
  29098. * @param {NodeUniform} nodeUniform - The node uniform.
  29099. */
  29100. constructor( nodeUniform ) {
  29101. super( nodeUniform.name, nodeUniform.value );
  29102. /**
  29103. * The node uniform.
  29104. *
  29105. * @type {NodeUniform}
  29106. */
  29107. this.nodeUniform = nodeUniform;
  29108. }
  29109. /**
  29110. * Overwritten to return the value of the node uniform.
  29111. *
  29112. * @return {Vector2} The value.
  29113. */
  29114. getValue() {
  29115. return this.nodeUniform.value;
  29116. }
  29117. /**
  29118. * Returns the node uniform data type.
  29119. *
  29120. * @return {String} The data type.
  29121. */
  29122. getType() {
  29123. return this.nodeUniform.type;
  29124. }
  29125. }
  29126. /**
  29127. * A special form of Vector3 uniform binding type.
  29128. * It's value is managed by a node object.
  29129. *
  29130. * @private
  29131. * @augments Vector3Uniform
  29132. */
  29133. class Vector3NodeUniform extends Vector3Uniform {
  29134. /**
  29135. * Constructs a new node-based Vector3 uniform.
  29136. *
  29137. * @param {NodeUniform} nodeUniform - The node uniform.
  29138. */
  29139. constructor( nodeUniform ) {
  29140. super( nodeUniform.name, nodeUniform.value );
  29141. /**
  29142. * The node uniform.
  29143. *
  29144. * @type {NodeUniform}
  29145. */
  29146. this.nodeUniform = nodeUniform;
  29147. }
  29148. /**
  29149. * Overwritten to return the value of the node uniform.
  29150. *
  29151. * @return {Vector3} The value.
  29152. */
  29153. getValue() {
  29154. return this.nodeUniform.value;
  29155. }
  29156. /**
  29157. * Returns the node uniform data type.
  29158. *
  29159. * @return {String} The data type.
  29160. */
  29161. getType() {
  29162. return this.nodeUniform.type;
  29163. }
  29164. }
  29165. /**
  29166. * A special form of Vector4 uniform binding type.
  29167. * It's value is managed by a node object.
  29168. *
  29169. * @private
  29170. * @augments Vector4Uniform
  29171. */
  29172. class Vector4NodeUniform extends Vector4Uniform {
  29173. /**
  29174. * Constructs a new node-based Vector4 uniform.
  29175. *
  29176. * @param {NodeUniform} nodeUniform - The node uniform.
  29177. */
  29178. constructor( nodeUniform ) {
  29179. super( nodeUniform.name, nodeUniform.value );
  29180. /**
  29181. * The node uniform.
  29182. *
  29183. * @type {NodeUniform}
  29184. */
  29185. this.nodeUniform = nodeUniform;
  29186. }
  29187. /**
  29188. * Overwritten to return the value of the node uniform.
  29189. *
  29190. * @return {Vector4} The value.
  29191. */
  29192. getValue() {
  29193. return this.nodeUniform.value;
  29194. }
  29195. /**
  29196. * Returns the node uniform data type.
  29197. *
  29198. * @return {String} The data type.
  29199. */
  29200. getType() {
  29201. return this.nodeUniform.type;
  29202. }
  29203. }
  29204. /**
  29205. * A special form of Color uniform binding type.
  29206. * It's value is managed by a node object.
  29207. *
  29208. * @private
  29209. * @augments ColorUniform
  29210. */
  29211. class ColorNodeUniform extends ColorUniform {
  29212. /**
  29213. * Constructs a new node-based Color uniform.
  29214. *
  29215. * @param {NodeUniform} nodeUniform - The node uniform.
  29216. */
  29217. constructor( nodeUniform ) {
  29218. super( nodeUniform.name, nodeUniform.value );
  29219. /**
  29220. * The node uniform.
  29221. *
  29222. * @type {NodeUniform}
  29223. */
  29224. this.nodeUniform = nodeUniform;
  29225. }
  29226. /**
  29227. * Overwritten to return the value of the node uniform.
  29228. *
  29229. * @return {Color} The value.
  29230. */
  29231. getValue() {
  29232. return this.nodeUniform.value;
  29233. }
  29234. /**
  29235. * Returns the node uniform data type.
  29236. *
  29237. * @return {String} The data type.
  29238. */
  29239. getType() {
  29240. return this.nodeUniform.type;
  29241. }
  29242. }
  29243. /**
  29244. * A special form of Matrix2 uniform binding type.
  29245. * It's value is managed by a node object.
  29246. *
  29247. * @private
  29248. * @augments Matrix2Uniform
  29249. */
  29250. class Matrix2NodeUniform extends Matrix2Uniform {
  29251. /**
  29252. * Constructs a new node-based Matrix2 uniform.
  29253. *
  29254. * @param {NodeUniform} nodeUniform - The node uniform.
  29255. */
  29256. constructor( nodeUniform ) {
  29257. super( nodeUniform.name, nodeUniform.value );
  29258. /**
  29259. * The node uniform.
  29260. *
  29261. * @type {NodeUniform}
  29262. */
  29263. this.nodeUniform = nodeUniform;
  29264. }
  29265. /**
  29266. * Overwritten to return the value of the node uniform.
  29267. *
  29268. * @return {Matrix2} The value.
  29269. */
  29270. getValue() {
  29271. return this.nodeUniform.value;
  29272. }
  29273. /**
  29274. * Returns the node uniform data type.
  29275. *
  29276. * @return {String} The data type.
  29277. */
  29278. getType() {
  29279. return this.nodeUniform.type;
  29280. }
  29281. }
  29282. /**
  29283. * A special form of Matrix3 uniform binding type.
  29284. * It's value is managed by a node object.
  29285. *
  29286. * @private
  29287. * @augments Matrix3Uniform
  29288. */
  29289. class Matrix3NodeUniform extends Matrix3Uniform {
  29290. /**
  29291. * Constructs a new node-based Matrix3 uniform.
  29292. *
  29293. * @param {NodeUniform} nodeUniform - The node uniform.
  29294. */
  29295. constructor( nodeUniform ) {
  29296. super( nodeUniform.name, nodeUniform.value );
  29297. /**
  29298. * The node uniform.
  29299. *
  29300. * @type {NodeUniform}
  29301. */
  29302. this.nodeUniform = nodeUniform;
  29303. }
  29304. /**
  29305. * Overwritten to return the value of the node uniform.
  29306. *
  29307. * @return {Matrix3} The value.
  29308. */
  29309. getValue() {
  29310. return this.nodeUniform.value;
  29311. }
  29312. /**
  29313. * Returns the node uniform data type.
  29314. *
  29315. * @return {String} The data type.
  29316. */
  29317. getType() {
  29318. return this.nodeUniform.type;
  29319. }
  29320. }
  29321. /**
  29322. * A special form of Matrix4 uniform binding type.
  29323. * It's value is managed by a node object.
  29324. *
  29325. * @private
  29326. * @augments Matrix4Uniform
  29327. */
  29328. class Matrix4NodeUniform extends Matrix4Uniform {
  29329. /**
  29330. * Constructs a new node-based Matrix4 uniform.
  29331. *
  29332. * @param {NodeUniform} nodeUniform - The node uniform.
  29333. */
  29334. constructor( nodeUniform ) {
  29335. super( nodeUniform.name, nodeUniform.value );
  29336. /**
  29337. * The node uniform.
  29338. *
  29339. * @type {NodeUniform}
  29340. */
  29341. this.nodeUniform = nodeUniform;
  29342. }
  29343. /**
  29344. * Overwritten to return the value of the node uniform.
  29345. *
  29346. * @return {Matrix4} The value.
  29347. */
  29348. getValue() {
  29349. return this.nodeUniform.value;
  29350. }
  29351. /**
  29352. * Returns the node uniform data type.
  29353. *
  29354. * @return {String} The data type.
  29355. */
  29356. getType() {
  29357. return this.nodeUniform.type;
  29358. }
  29359. }
  29360. const LOD_MIN = 4;
  29361. // The standard deviations (radians) associated with the extra mips. These are
  29362. // chosen to approximate a Trowbridge-Reitz distribution function times the
  29363. // geometric shadowing function. These sigma values squared must match the
  29364. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  29365. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  29366. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  29367. // samples and exit early, but not recompile the shader.
  29368. const MAX_SAMPLES = 20;
  29369. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  29370. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  29371. const _clearColor = /*@__PURE__*/ new Color();
  29372. let _oldTarget = null;
  29373. let _oldActiveCubeFace = 0;
  29374. let _oldActiveMipmapLevel = 0;
  29375. // Golden Ratio
  29376. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29377. const INV_PHI = 1 / PHI;
  29378. // Vertices of a dodecahedron (except the opposites, which represent the
  29379. // same axis), used as axis directions evenly spread on a sphere.
  29380. const _axisDirections = [
  29381. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  29382. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  29383. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  29384. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  29385. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  29386. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  29387. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  29388. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  29389. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  29390. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  29391. ];
  29392. // maps blur materials to their uniforms dictionary
  29393. const _uniformsMap = new WeakMap();
  29394. // WebGPU Face indices
  29395. const _faceLib = [
  29396. 3, 1, 5,
  29397. 0, 4, 2
  29398. ];
  29399. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  29400. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  29401. /**
  29402. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  29403. * (PMREM) from a cubeMap environment texture. This allows different levels of
  29404. * blur to be quickly accessed based on material roughness. It is packed into a
  29405. * special CubeUV format that allows us to perform custom interpolation so that
  29406. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  29407. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  29408. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  29409. * higher roughness levels. In this way we maintain resolution to smoothly
  29410. * interpolate diffuse lighting while limiting sampling computation.
  29411. *
  29412. * Paper: Fast, Accurate Image-Based Lighting
  29413. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  29414. */
  29415. class PMREMGenerator {
  29416. constructor( renderer ) {
  29417. this._renderer = renderer;
  29418. this._pingPongRenderTarget = null;
  29419. this._lodMax = 0;
  29420. this._cubeSize = 0;
  29421. this._lodPlanes = [];
  29422. this._sizeLods = [];
  29423. this._sigmas = [];
  29424. this._lodMeshes = [];
  29425. this._blurMaterial = null;
  29426. this._cubemapMaterial = null;
  29427. this._equirectMaterial = null;
  29428. this._backgroundBox = null;
  29429. }
  29430. get _hasInitialized() {
  29431. return this._renderer.hasInitialized();
  29432. }
  29433. /**
  29434. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29435. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29436. * in radians to be applied to the scene before PMREM generation. Optional near
  29437. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29438. * is placed at the origin).
  29439. *
  29440. * @param {Scene} scene - The scene to be captured.
  29441. * @param {Number} [sigma=0] - The blur radius in radians.
  29442. * @param {Number} [near=0.1] - The near plane distance.
  29443. * @param {Number} [far=100] - The far plane distance.
  29444. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29445. * @return {RenderTarget} The resulting PMREM.
  29446. * @see fromSceneAsync
  29447. */
  29448. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29449. this._setSize( 256 );
  29450. if ( this._hasInitialized === false ) {
  29451. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  29452. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29453. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  29454. return cubeUVRenderTarget;
  29455. }
  29456. _oldTarget = this._renderer.getRenderTarget();
  29457. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29458. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29459. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29460. cubeUVRenderTarget.depthBuffer = true;
  29461. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  29462. if ( sigma > 0 ) {
  29463. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29464. }
  29465. this._applyPMREM( cubeUVRenderTarget );
  29466. this._cleanup( cubeUVRenderTarget );
  29467. return cubeUVRenderTarget;
  29468. }
  29469. /**
  29470. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29471. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29472. * in radians to be applied to the scene before PMREM generation. Optional near
  29473. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29474. * is placed at the origin).
  29475. *
  29476. * @param {Scene} scene - The scene to be captured.
  29477. * @param {Number} [sigma=0] - The blur radius in radians.
  29478. * @param {Number} [near=0.1] - The near plane distance.
  29479. * @param {Number} [far=100] - The far plane distance.
  29480. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29481. * @return {Promise<RenderTarget>} The resulting PMREM.
  29482. * @see fromScene
  29483. */
  29484. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29485. if ( this._hasInitialized === false ) await this._renderer.init();
  29486. return this.fromScene( scene, sigma, near, far, renderTarget );
  29487. }
  29488. /**
  29489. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29490. * or HDR. The ideal input image size is 1k (1024 x 512),
  29491. * as this matches best with the 256 x 256 cubemap output.
  29492. *
  29493. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29494. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29495. * @return {RenderTarget} The resulting PMREM.
  29496. * @see fromEquirectangularAsync
  29497. */
  29498. fromEquirectangular( equirectangular, renderTarget = null ) {
  29499. if ( this._hasInitialized === false ) {
  29500. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  29501. this._setSizeFromTexture( equirectangular );
  29502. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29503. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  29504. return cubeUVRenderTarget;
  29505. }
  29506. return this._fromTexture( equirectangular, renderTarget );
  29507. }
  29508. /**
  29509. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29510. * or HDR. The ideal input image size is 1k (1024 x 512),
  29511. * as this matches best with the 256 x 256 cubemap output.
  29512. *
  29513. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29514. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29515. * @return {Promise<RenderTarget>} The resulting PMREM.
  29516. * @see fromEquirectangular
  29517. */
  29518. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  29519. if ( this._hasInitialized === false ) await this._renderer.init();
  29520. return this._fromTexture( equirectangular, renderTarget );
  29521. }
  29522. /**
  29523. * Generates a PMREM from an cubemap texture, which can be either LDR
  29524. * or HDR. The ideal input cube size is 256 x 256,
  29525. * as this matches best with the 256 x 256 cubemap output.
  29526. *
  29527. * @param {Texture} cubemap - The cubemap texture to be converted.
  29528. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29529. * @return {RenderTarget} The resulting PMREM.
  29530. * @see fromCubemapAsync
  29531. */
  29532. fromCubemap( cubemap, renderTarget = null ) {
  29533. if ( this._hasInitialized === false ) {
  29534. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  29535. this._setSizeFromTexture( cubemap );
  29536. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29537. this.fromCubemapAsync( cubemap, renderTarget );
  29538. return cubeUVRenderTarget;
  29539. }
  29540. return this._fromTexture( cubemap, renderTarget );
  29541. }
  29542. /**
  29543. * Generates a PMREM from an cubemap texture, which can be either LDR
  29544. * or HDR. The ideal input cube size is 256 x 256,
  29545. * with the 256 x 256 cubemap output.
  29546. *
  29547. * @param {Texture} cubemap - The cubemap texture to be converted.
  29548. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29549. * @return {Promise<RenderTarget>} The resulting PMREM.
  29550. * @see fromCubemap
  29551. */
  29552. async fromCubemapAsync( cubemap, renderTarget = null ) {
  29553. if ( this._hasInitialized === false ) await this._renderer.init();
  29554. return this._fromTexture( cubemap, renderTarget );
  29555. }
  29556. /**
  29557. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29558. * your texture's network fetch for increased concurrency.
  29559. *
  29560. * @returns {Promise}
  29561. */
  29562. async compileCubemapShader() {
  29563. if ( this._cubemapMaterial === null ) {
  29564. this._cubemapMaterial = _getCubemapMaterial();
  29565. await this._compileMaterial( this._cubemapMaterial );
  29566. }
  29567. }
  29568. /**
  29569. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29570. * your texture's network fetch for increased concurrency.
  29571. *
  29572. * @returns {Promise}
  29573. */
  29574. async compileEquirectangularShader() {
  29575. if ( this._equirectMaterial === null ) {
  29576. this._equirectMaterial = _getEquirectMaterial();
  29577. await this._compileMaterial( this._equirectMaterial );
  29578. }
  29579. }
  29580. /**
  29581. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29582. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29583. * one of them will cause any others to also become unusable.
  29584. */
  29585. dispose() {
  29586. this._dispose();
  29587. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  29588. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  29589. if ( this._backgroundBox !== null ) {
  29590. this._backgroundBox.geometry.dispose();
  29591. this._backgroundBox.material.dispose();
  29592. }
  29593. }
  29594. // private interface
  29595. _setSizeFromTexture( texture ) {
  29596. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  29597. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  29598. } else { // Equirectangular
  29599. this._setSize( texture.image.width / 4 );
  29600. }
  29601. }
  29602. _setSize( cubeSize ) {
  29603. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  29604. this._cubeSize = Math.pow( 2, this._lodMax );
  29605. }
  29606. _dispose() {
  29607. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  29608. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  29609. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  29610. this._lodPlanes[ i ].dispose();
  29611. }
  29612. }
  29613. _cleanup( outputTarget ) {
  29614. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  29615. outputTarget.scissorTest = false;
  29616. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29617. }
  29618. _fromTexture( texture, renderTarget ) {
  29619. this._setSizeFromTexture( texture );
  29620. _oldTarget = this._renderer.getRenderTarget();
  29621. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29622. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29623. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29624. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29625. this._applyPMREM( cubeUVRenderTarget );
  29626. this._cleanup( cubeUVRenderTarget );
  29627. return cubeUVRenderTarget;
  29628. }
  29629. _allocateTargets() {
  29630. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  29631. const height = 4 * this._cubeSize;
  29632. const params = {
  29633. magFilter: LinearFilter,
  29634. minFilter: LinearFilter,
  29635. generateMipmaps: false,
  29636. type: HalfFloatType,
  29637. format: RGBAFormat,
  29638. colorSpace: LinearSRGBColorSpace,
  29639. //depthBuffer: false
  29640. };
  29641. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  29642. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  29643. if ( this._pingPongRenderTarget !== null ) {
  29644. this._dispose();
  29645. }
  29646. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  29647. const { _lodMax } = this;
  29648. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  29649. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  29650. }
  29651. return cubeUVRenderTarget;
  29652. }
  29653. async _compileMaterial( material ) {
  29654. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  29655. await this._renderer.compile( tmpMesh, _flatCamera );
  29656. }
  29657. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29658. const cubeCamera = _cubeCamera;
  29659. cubeCamera.near = near;
  29660. cubeCamera.far = far;
  29661. // px, py, pz, nx, ny, nz
  29662. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  29663. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  29664. const renderer = this._renderer;
  29665. const originalAutoClear = renderer.autoClear;
  29666. renderer.getClearColor( _clearColor );
  29667. renderer.autoClear = false;
  29668. let backgroundBox = this._backgroundBox;
  29669. if ( backgroundBox === null ) {
  29670. const backgroundMaterial = new MeshBasicMaterial( {
  29671. name: 'PMREM.Background',
  29672. side: BackSide,
  29673. depthWrite: false,
  29674. depthTest: false
  29675. } );
  29676. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  29677. }
  29678. let useSolidColor = false;
  29679. const background = scene.background;
  29680. if ( background ) {
  29681. if ( background.isColor ) {
  29682. backgroundBox.material.color.copy( background );
  29683. scene.background = null;
  29684. useSolidColor = true;
  29685. }
  29686. } else {
  29687. backgroundBox.material.color.copy( _clearColor );
  29688. useSolidColor = true;
  29689. }
  29690. renderer.setRenderTarget( cubeUVRenderTarget );
  29691. renderer.clear();
  29692. if ( useSolidColor ) {
  29693. renderer.render( backgroundBox, cubeCamera );
  29694. }
  29695. for ( let i = 0; i < 6; i ++ ) {
  29696. const col = i % 3;
  29697. if ( col === 0 ) {
  29698. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29699. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29700. } else if ( col === 1 ) {
  29701. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29702. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29703. } else {
  29704. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29705. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29706. }
  29707. const size = this._cubeSize;
  29708. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  29709. renderer.render( scene, cubeCamera );
  29710. }
  29711. renderer.autoClear = originalAutoClear;
  29712. scene.background = background;
  29713. }
  29714. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29715. const renderer = this._renderer;
  29716. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  29717. if ( isCubeTexture ) {
  29718. if ( this._cubemapMaterial === null ) {
  29719. this._cubemapMaterial = _getCubemapMaterial( texture );
  29720. }
  29721. } else {
  29722. if ( this._equirectMaterial === null ) {
  29723. this._equirectMaterial = _getEquirectMaterial( texture );
  29724. }
  29725. }
  29726. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  29727. material.fragmentNode.value = texture;
  29728. const mesh = this._lodMeshes[ 0 ];
  29729. mesh.material = material;
  29730. const size = this._cubeSize;
  29731. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  29732. renderer.setRenderTarget( cubeUVRenderTarget );
  29733. renderer.render( mesh, _flatCamera );
  29734. }
  29735. _applyPMREM( cubeUVRenderTarget ) {
  29736. const renderer = this._renderer;
  29737. const autoClear = renderer.autoClear;
  29738. renderer.autoClear = false;
  29739. const n = this._lodPlanes.length;
  29740. for ( let i = 1; i < n; i ++ ) {
  29741. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  29742. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  29743. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29744. }
  29745. renderer.autoClear = autoClear;
  29746. }
  29747. /**
  29748. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29749. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29750. * the blur latitudinally (around the poles), and then longitudinally (towards
  29751. * the poles) to approximate the orthogonally-separable blur. It is least
  29752. * accurate at the poles, but still does a decent job.
  29753. *
  29754. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  29755. * @param {Number} lodIn - The input level-of-detail.
  29756. * @param {Number} lodOut - The output level-of-detail.
  29757. * @param {Number} sigma - The blur radius in radians.
  29758. * @param {Vector3} [poleAxis] - The pole axis.
  29759. */
  29760. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29761. const pingPongRenderTarget = this._pingPongRenderTarget;
  29762. this._halfBlur(
  29763. cubeUVRenderTarget,
  29764. pingPongRenderTarget,
  29765. lodIn,
  29766. lodOut,
  29767. sigma,
  29768. 'latitudinal',
  29769. poleAxis );
  29770. this._halfBlur(
  29771. pingPongRenderTarget,
  29772. cubeUVRenderTarget,
  29773. lodOut,
  29774. lodOut,
  29775. sigma,
  29776. 'longitudinal',
  29777. poleAxis );
  29778. }
  29779. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29780. const renderer = this._renderer;
  29781. const blurMaterial = this._blurMaterial;
  29782. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29783. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  29784. }
  29785. // Number of standard deviations at which to cut off the discrete approximation.
  29786. const STANDARD_DEVIATIONS = 3;
  29787. const blurMesh = this._lodMeshes[ lodOut ];
  29788. blurMesh.material = blurMaterial;
  29789. const blurUniforms = _uniformsMap.get( blurMaterial );
  29790. const pixels = this._sizeLods[ lodIn ] - 1;
  29791. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29792. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29793. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29794. if ( samples > MAX_SAMPLES ) {
  29795. console.warn( `sigmaRadians, ${
  29796. sigmaRadians}, is too large and will clip, as it requested ${
  29797. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29798. }
  29799. const weights = [];
  29800. let sum = 0;
  29801. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29802. const x = i / sigmaPixels;
  29803. const weight = Math.exp( - x * x / 2 );
  29804. weights.push( weight );
  29805. if ( i === 0 ) {
  29806. sum += weight;
  29807. } else if ( i < samples ) {
  29808. sum += 2 * weight;
  29809. }
  29810. }
  29811. for ( let i = 0; i < weights.length; i ++ ) {
  29812. weights[ i ] = weights[ i ] / sum;
  29813. }
  29814. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  29815. blurUniforms.envMap.value = targetIn.texture;
  29816. blurUniforms.samples.value = samples;
  29817. blurUniforms.weights.array = weights;
  29818. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  29819. if ( poleAxis ) {
  29820. blurUniforms.poleAxis.value = poleAxis;
  29821. }
  29822. const { _lodMax } = this;
  29823. blurUniforms.dTheta.value = radiansPerPixel;
  29824. blurUniforms.mipInt.value = _lodMax - lodIn;
  29825. const outputSize = this._sizeLods[ lodOut ];
  29826. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  29827. const y = 4 * ( this._cubeSize - outputSize );
  29828. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29829. renderer.setRenderTarget( targetOut );
  29830. renderer.render( blurMesh, _flatCamera );
  29831. }
  29832. }
  29833. function _createPlanes( lodMax ) {
  29834. const lodPlanes = [];
  29835. const sizeLods = [];
  29836. const sigmas = [];
  29837. const lodMeshes = [];
  29838. let lod = lodMax;
  29839. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29840. for ( let i = 0; i < totalLods; i ++ ) {
  29841. const sizeLod = Math.pow( 2, lod );
  29842. sizeLods.push( sizeLod );
  29843. let sigma = 1.0 / sizeLod;
  29844. if ( i > lodMax - LOD_MIN ) {
  29845. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29846. } else if ( i === 0 ) {
  29847. sigma = 0;
  29848. }
  29849. sigmas.push( sigma );
  29850. const texelSize = 1.0 / ( sizeLod - 2 );
  29851. const min = - texelSize;
  29852. const max = 1 + texelSize;
  29853. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29854. const cubeFaces = 6;
  29855. const vertices = 6;
  29856. const positionSize = 3;
  29857. const uvSize = 2;
  29858. const faceIndexSize = 1;
  29859. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29860. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29861. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29862. for ( let face = 0; face < cubeFaces; face ++ ) {
  29863. const x = ( face % 3 ) * 2 / 3 - 1;
  29864. const y = face > 2 ? 0 : - 1;
  29865. const coordinates = [
  29866. x, y, 0,
  29867. x + 2 / 3, y, 0,
  29868. x + 2 / 3, y + 1, 0,
  29869. x, y, 0,
  29870. x + 2 / 3, y + 1, 0,
  29871. x, y + 1, 0
  29872. ];
  29873. const faceIdx = _faceLib[ face ];
  29874. position.set( coordinates, positionSize * vertices * faceIdx );
  29875. uv.set( uv1, uvSize * vertices * faceIdx );
  29876. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29877. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29878. }
  29879. const planes = new BufferGeometry();
  29880. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29881. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29882. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29883. lodPlanes.push( planes );
  29884. lodMeshes.push( new Mesh( planes, null ) );
  29885. if ( lod > LOD_MIN ) {
  29886. lod --;
  29887. }
  29888. }
  29889. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29890. }
  29891. function _createRenderTarget( width, height, params ) {
  29892. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29893. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29894. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29895. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29896. cubeUVRenderTarget.scissorTest = true;
  29897. return cubeUVRenderTarget;
  29898. }
  29899. function _setViewport( target, x, y, width, height ) {
  29900. target.viewport.set( x, y, width, height );
  29901. target.scissor.set( x, y, width, height );
  29902. }
  29903. function _getMaterial( type ) {
  29904. const material = new NodeMaterial();
  29905. material.depthTest = false;
  29906. material.depthWrite = false;
  29907. material.blending = NoBlending;
  29908. material.name = `PMREM_${ type }`;
  29909. return material;
  29910. }
  29911. function _getBlurShader( lodMax, width, height ) {
  29912. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29913. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29914. const dTheta = uniform( 0 );
  29915. const n = float( MAX_SAMPLES );
  29916. const latitudinal = uniform( 0 ); // false, bool
  29917. const samples = uniform( 1 ); // int
  29918. const envMap = texture( null );
  29919. const mipInt = uniform( 0 ); // int
  29920. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29921. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29922. const CUBEUV_MAX_MIP = float( lodMax );
  29923. const materialUniforms = {
  29924. n,
  29925. latitudinal,
  29926. weights,
  29927. poleAxis,
  29928. outputDirection: _outputDirection,
  29929. dTheta,
  29930. samples,
  29931. envMap,
  29932. mipInt,
  29933. CUBEUV_TEXEL_WIDTH,
  29934. CUBEUV_TEXEL_HEIGHT,
  29935. CUBEUV_MAX_MIP
  29936. };
  29937. const material = _getMaterial( 'blur' );
  29938. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29939. _uniformsMap.set( material, materialUniforms );
  29940. return material;
  29941. }
  29942. function _getCubemapMaterial( envTexture ) {
  29943. const material = _getMaterial( 'cubemap' );
  29944. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  29945. return material;
  29946. }
  29947. function _getEquirectMaterial( envTexture ) {
  29948. const material = _getMaterial( 'equirect' );
  29949. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  29950. return material;
  29951. }
  29952. const rendererCache = new WeakMap();
  29953. const typeFromArray = new Map( [
  29954. [ Int8Array, 'int' ],
  29955. [ Int16Array, 'int' ],
  29956. [ Int32Array, 'int' ],
  29957. [ Uint8Array, 'uint' ],
  29958. [ Uint16Array, 'uint' ],
  29959. [ Uint32Array, 'uint' ],
  29960. [ Float32Array, 'float' ]
  29961. ] );
  29962. const toFloat = ( value ) => {
  29963. if ( /e/g.test( value ) ) {
  29964. return String( value ).replace( /\+/g, '' );
  29965. } else {
  29966. value = Number( value );
  29967. return value + ( value % 1 ? '' : '.0' );
  29968. }
  29969. };
  29970. /**
  29971. * Base class for builders which generate a shader program based
  29972. * on a 3D object and its node material definition.
  29973. */
  29974. class NodeBuilder {
  29975. /**
  29976. * Constructs a new node builder.
  29977. *
  29978. * @param {Object3D} object - The 3D object.
  29979. * @param {Renderer} renderer - The current renderer.
  29980. * @param {NodeParser} parser - A reference to a node parser.
  29981. */
  29982. constructor( object, renderer, parser ) {
  29983. /**
  29984. * The 3D object.
  29985. *
  29986. * @type {Object3D}
  29987. */
  29988. this.object = object;
  29989. /**
  29990. * The material of the 3D object.
  29991. *
  29992. * @type {Material?}
  29993. */
  29994. this.material = ( object && object.material ) || null;
  29995. /**
  29996. * The geometry of the 3D object.
  29997. *
  29998. * @type {BufferGeometry?}
  29999. */
  30000. this.geometry = ( object && object.geometry ) || null;
  30001. /**
  30002. * The current renderer.
  30003. *
  30004. * @type {Renderer}
  30005. */
  30006. this.renderer = renderer;
  30007. /**
  30008. * A reference to a node parser.
  30009. *
  30010. * @type {NodeParser}
  30011. */
  30012. this.parser = parser;
  30013. /**
  30014. * The scene the 3D object belongs to.
  30015. *
  30016. * @type {Scene?}
  30017. * @default null
  30018. */
  30019. this.scene = null;
  30020. /**
  30021. * The camera the 3D object is rendered with.
  30022. *
  30023. * @type {Camera?}
  30024. * @default null
  30025. */
  30026. this.camera = null;
  30027. /**
  30028. * A list of all nodes the builder is processing
  30029. * for this 3D object.
  30030. *
  30031. * @type {Array<Node>}
  30032. */
  30033. this.nodes = [];
  30034. /**
  30035. * A list of all sequential nodes.
  30036. *
  30037. * @type {Array<Node>}
  30038. */
  30039. this.sequentialNodes = [];
  30040. /**
  30041. * A list of all nodes which {@link Node#update} method should be executed.
  30042. *
  30043. * @type {Array<Node>}
  30044. */
  30045. this.updateNodes = [];
  30046. /**
  30047. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  30048. *
  30049. * @type {Array<Node>}
  30050. */
  30051. this.updateBeforeNodes = [];
  30052. /**
  30053. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  30054. *
  30055. * @type {Array<Node>}
  30056. */
  30057. this.updateAfterNodes = [];
  30058. /**
  30059. * A dictionary that assigns each node to a unique hash.
  30060. *
  30061. * @type {Object<Number,Node>}
  30062. */
  30063. this.hashNodes = {};
  30064. /**
  30065. * A reference to a node material observer.
  30066. *
  30067. * @type {NodeMaterialObserver?}
  30068. * @default null
  30069. */
  30070. this.observer = null;
  30071. /**
  30072. * A reference to the current lights node.
  30073. *
  30074. * @type {LightsNode?}
  30075. * @default null
  30076. */
  30077. this.lightsNode = null;
  30078. /**
  30079. * A reference to the current environment node.
  30080. *
  30081. * @type {Node?}
  30082. * @default null
  30083. */
  30084. this.environmentNode = null;
  30085. /**
  30086. * A reference to the current fog node.
  30087. *
  30088. * @type {FogNode?}
  30089. * @default null
  30090. */
  30091. this.fogNode = null;
  30092. /**
  30093. * The current clipping context.
  30094. *
  30095. * @type {ClippingContext?}
  30096. */
  30097. this.clippingContext = null;
  30098. /**
  30099. * The generated vertex shader.
  30100. *
  30101. * @type {String?}
  30102. */
  30103. this.vertexShader = null;
  30104. /**
  30105. * The generated fragment shader.
  30106. *
  30107. * @type {String?}
  30108. */
  30109. this.fragmentShader = null;
  30110. /**
  30111. * The generated compute shader.
  30112. *
  30113. * @type {String?}
  30114. */
  30115. this.computeShader = null;
  30116. /**
  30117. * Nodes used in the primary flow of code generation.
  30118. *
  30119. * @type {Object<String,Array<Node>>}
  30120. */
  30121. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  30122. /**
  30123. * Nodes code from `.flowNodes`.
  30124. *
  30125. * @type {Object<String,String>}
  30126. */
  30127. this.flowCode = { vertex: '', fragment: '', compute: '' };
  30128. /**
  30129. * This dictionary holds the node uniforms of the builder.
  30130. * The uniforms are maintained in an array for each shader stage.
  30131. *
  30132. * @type {Object}
  30133. */
  30134. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  30135. /**
  30136. * This dictionary holds the output structs of the builder.
  30137. * The structs are maintained in an array for each shader stage.
  30138. *
  30139. * @type {Object}
  30140. */
  30141. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  30142. /**
  30143. * This dictionary holds the bindings for each shader stage.
  30144. *
  30145. * @type {Object}
  30146. */
  30147. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  30148. /**
  30149. * This dictionary maintains the binding indices per bind group.
  30150. *
  30151. * @type {Object}
  30152. */
  30153. this.bindingsIndexes = {};
  30154. /**
  30155. * Reference to the array of bind groups.
  30156. *
  30157. * @type {Array<BindGroup>?}
  30158. */
  30159. this.bindGroups = null;
  30160. /**
  30161. * This array holds the node attributes of this builder
  30162. * created via {@link AttributeNode}.
  30163. *
  30164. * @type {Array<NodeAttribute>}
  30165. */
  30166. this.attributes = [];
  30167. /**
  30168. * This array holds the node attributes of this builder
  30169. * created via {@link BufferAttributeNode}.
  30170. *
  30171. * @type {Array<NodeAttribute>}
  30172. */
  30173. this.bufferAttributes = [];
  30174. /**
  30175. * This array holds the node varyings of this builder.
  30176. *
  30177. * @type {Array<NodeVarying>}
  30178. */
  30179. this.varyings = [];
  30180. /**
  30181. * This dictionary holds the (native) node codes of this builder.
  30182. * The codes are maintained in an array for each shader stage.
  30183. *
  30184. * @type {Object<String,Array<NodeCode>>}
  30185. */
  30186. this.codes = {};
  30187. /**
  30188. * This dictionary holds the node variables of this builder.
  30189. * The variables are maintained in an array for each shader stage.
  30190. *
  30191. * @type {Object<String,Array<NodeVar>>}
  30192. */
  30193. this.vars = {};
  30194. /**
  30195. * Current code flow.
  30196. * All code generated in this stack will be stored in `.flow`.
  30197. *
  30198. * @type {{code: String}}
  30199. */
  30200. this.flow = { code: '' };
  30201. /**
  30202. * A chain of nodes.
  30203. * Used to check recursive calls in node-graph.
  30204. *
  30205. * @type {Array<Node>}
  30206. */
  30207. this.chaining = [];
  30208. /**
  30209. * The current stack.
  30210. * This reflects the current process in the code block hierarchy,
  30211. * it is useful to know if the current process is inside a conditional for example.
  30212. *
  30213. * @type {StackNode}
  30214. */
  30215. this.stack = stack();
  30216. /**
  30217. * List of stack nodes.
  30218. * The current stack hierarchy is stored in an array.
  30219. *
  30220. * @type {Array<StackNode>}
  30221. */
  30222. this.stacks = [];
  30223. /**
  30224. * A tab value. Used for shader string generation.
  30225. *
  30226. * @type {String}
  30227. * @default '\t'
  30228. */
  30229. this.tab = '\t';
  30230. /**
  30231. * Reference to the current function node.
  30232. *
  30233. * @type {FunctionNode?}
  30234. * @default null
  30235. */
  30236. this.currentFunctionNode = null;
  30237. /**
  30238. * The builder's context.
  30239. *
  30240. * @type {Object}
  30241. */
  30242. this.context = {
  30243. material: this.material
  30244. };
  30245. /**
  30246. * The builder's cache.
  30247. *
  30248. * @type {NodeCache}
  30249. */
  30250. this.cache = new NodeCache();
  30251. /**
  30252. * Since the {@link NodeBuilder#cache} might be temporarily
  30253. * overwritten by other caches, this member retains the reference
  30254. * to the builder's own cache.
  30255. *
  30256. * @type {NodeCache}
  30257. * @default this.cache
  30258. */
  30259. this.globalCache = this.cache;
  30260. this.flowsData = new WeakMap();
  30261. /**
  30262. * The current shader stage.
  30263. *
  30264. * @type {('vertex'|'fragment'|'compute'|'any')?}
  30265. */
  30266. this.shaderStage = null;
  30267. /**
  30268. * The current build stage.
  30269. *
  30270. * @type {('setup'|'analyze'|'generate')?}
  30271. */
  30272. this.buildStage = null;
  30273. /**
  30274. * Whether comparison in shader code are generated with methods or not.
  30275. *
  30276. * @type {Boolean}
  30277. * @default false
  30278. */
  30279. this.useComparisonMethod = false;
  30280. }
  30281. /**
  30282. * Returns the bind groups of the current renderer.
  30283. *
  30284. * @return {ChainMap} The cache.
  30285. */
  30286. getBindGroupsCache() {
  30287. let bindGroupsCache = rendererCache.get( this.renderer );
  30288. if ( bindGroupsCache === undefined ) {
  30289. bindGroupsCache = new ChainMap();
  30290. rendererCache.set( this.renderer, bindGroupsCache );
  30291. }
  30292. return bindGroupsCache;
  30293. }
  30294. /**
  30295. * Factory method for creating an instance of {@link RenderTarget} with the given
  30296. * dimensions and options.
  30297. *
  30298. * @param {Number} width - The width of the render target.
  30299. * @param {Number} height - The height of the render target.
  30300. * @param {Object} options - The options of the render target.
  30301. * @return {RenderTarget} The render target.
  30302. */
  30303. createRenderTarget( width, height, options ) {
  30304. return new RenderTarget( width, height, options );
  30305. }
  30306. /**
  30307. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  30308. * dimensions and options.
  30309. *
  30310. * @param {Number} size - The size of the cube render target.
  30311. * @param {Object} options - The options of the cube render target.
  30312. * @return {CubeRenderTarget} The cube render target.
  30313. */
  30314. createCubeRenderTarget( size, options ) {
  30315. return new CubeRenderTarget( size, options );
  30316. }
  30317. /**
  30318. * Factory method for creating an instance of {@link PMREMGenerator}.
  30319. *
  30320. * @return {PMREMGenerator} The PMREM generator.
  30321. */
  30322. createPMREMGenerator() {
  30323. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  30324. return new PMREMGenerator( this.renderer );
  30325. }
  30326. /**
  30327. * Whether the given node is included in the internal array of nodes or not.
  30328. *
  30329. * @param {Node} node - The node to test.
  30330. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  30331. */
  30332. includes( node ) {
  30333. return this.nodes.includes( node );
  30334. }
  30335. /**
  30336. * Returns the output struct name which is required by
  30337. * {@link module:OutputStructNode}.
  30338. *
  30339. * @abstract
  30340. * @return {String} The name of the output struct.
  30341. */
  30342. getOutputStructName() {}
  30343. /**
  30344. * Returns a bind group for the given group name and binding.
  30345. *
  30346. * @private
  30347. * @param {String} groupName - The group name.
  30348. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  30349. * @return {BindGroup} The bind group
  30350. */
  30351. _getBindGroup( groupName, bindings ) {
  30352. const bindGroupsCache = this.getBindGroupsCache();
  30353. //
  30354. const bindingsArray = [];
  30355. let sharedGroup = true;
  30356. for ( const binding of bindings ) {
  30357. bindingsArray.push( binding );
  30358. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  30359. }
  30360. //
  30361. let bindGroup;
  30362. if ( sharedGroup ) {
  30363. bindGroup = bindGroupsCache.get( bindingsArray );
  30364. if ( bindGroup === undefined ) {
  30365. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30366. bindGroupsCache.set( bindingsArray, bindGroup );
  30367. }
  30368. } else {
  30369. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30370. }
  30371. return bindGroup;
  30372. }
  30373. /**
  30374. * Returns an array of node uniform groups for the given group name and shader stage.
  30375. *
  30376. * @param {String} groupName - The group name.
  30377. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30378. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  30379. */
  30380. getBindGroupArray( groupName, shaderStage ) {
  30381. const bindings = this.bindings[ shaderStage ];
  30382. let bindGroup = bindings[ groupName ];
  30383. if ( bindGroup === undefined ) {
  30384. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  30385. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  30386. }
  30387. bindings[ groupName ] = bindGroup = [];
  30388. }
  30389. return bindGroup;
  30390. }
  30391. /**
  30392. * Returns a list bindings of all shader stages separated by groups.
  30393. *
  30394. * @return {Array<BindGroup>} The list of bindings.
  30395. */
  30396. getBindings() {
  30397. let bindingsGroups = this.bindGroups;
  30398. if ( bindingsGroups === null ) {
  30399. const groups = {};
  30400. const bindings = this.bindings;
  30401. for ( const shaderStage of shaderStages ) {
  30402. for ( const groupName in bindings[ shaderStage ] ) {
  30403. const uniforms = bindings[ shaderStage ][ groupName ];
  30404. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  30405. groupUniforms.push( ...uniforms );
  30406. }
  30407. }
  30408. bindingsGroups = [];
  30409. for ( const groupName in groups ) {
  30410. const group = groups[ groupName ];
  30411. const bindingsGroup = this._getBindGroup( groupName, group );
  30412. bindingsGroups.push( bindingsGroup );
  30413. }
  30414. this.bindGroups = bindingsGroups;
  30415. }
  30416. return bindingsGroups;
  30417. }
  30418. /**
  30419. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  30420. */
  30421. sortBindingGroups() {
  30422. const bindingsGroups = this.getBindings();
  30423. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  30424. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  30425. const bindingGroup = bindingsGroups[ i ];
  30426. this.bindingsIndexes[ bindingGroup.name ].group = i;
  30427. bindingGroup.index = i;
  30428. }
  30429. }
  30430. /**
  30431. * The builder maintains each node in a hash-based dictionary.
  30432. * This method sets the given node (value) with the given hash (key) into this dictionary.
  30433. *
  30434. * @param {Node} node - The node to add.
  30435. * @param {Number} hash - The hash of the node.
  30436. */
  30437. setHashNode( node, hash ) {
  30438. this.hashNodes[ hash ] = node;
  30439. }
  30440. /**
  30441. * Adds a node to this builder.
  30442. *
  30443. * @param {Node} node - The node to add.
  30444. */
  30445. addNode( node ) {
  30446. if ( this.nodes.includes( node ) === false ) {
  30447. this.nodes.push( node );
  30448. this.setHashNode( node, node.getHash( this ) );
  30449. }
  30450. }
  30451. /**
  30452. * It is used to add Nodes that will be used as FRAME and RENDER events,
  30453. * and need to follow a certain sequence in the calls to work correctly.
  30454. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  30455. *
  30456. * @param {Node} node - The node to add.
  30457. */
  30458. addSequentialNode( node ) {
  30459. if ( this.sequentialNodes.includes( node ) === false ) {
  30460. this.sequentialNodes.push( node );
  30461. }
  30462. }
  30463. /**
  30464. * Checks the update types of nodes
  30465. */
  30466. buildUpdateNodes() {
  30467. for ( const node of this.nodes ) {
  30468. const updateType = node.getUpdateType();
  30469. if ( updateType !== NodeUpdateType.NONE ) {
  30470. this.updateNodes.push( node.getSelf() );
  30471. }
  30472. }
  30473. for ( const node of this.sequentialNodes ) {
  30474. const updateBeforeType = node.getUpdateBeforeType();
  30475. const updateAfterType = node.getUpdateAfterType();
  30476. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30477. this.updateBeforeNodes.push( node.getSelf() );
  30478. }
  30479. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30480. this.updateAfterNodes.push( node.getSelf() );
  30481. }
  30482. }
  30483. }
  30484. /**
  30485. * A reference the current node which is the
  30486. * last node in the chain of nodes.
  30487. *
  30488. * @type {Node}
  30489. */
  30490. get currentNode() {
  30491. return this.chaining[ this.chaining.length - 1 ];
  30492. }
  30493. /**
  30494. * Whether the given texture is filtered or not.
  30495. *
  30496. * @param {Texture} texture - The texture to check.
  30497. * @return {Boolean} Whether the given texture is filtered or not.
  30498. */
  30499. isFilteredTexture( texture ) {
  30500. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30501. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30502. }
  30503. /**
  30504. * Adds the given node to the internal node chain.
  30505. * This is used to check recursive calls in node-graph.
  30506. *
  30507. * @param {Node} node - The node to add.
  30508. */
  30509. addChain( node ) {
  30510. /*
  30511. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30512. console.warn( 'Recursive node: ', node );
  30513. }
  30514. */
  30515. this.chaining.push( node );
  30516. }
  30517. /**
  30518. * Removes the given node from the internal node chain.
  30519. *
  30520. * @param {Node} node - The node to remove.
  30521. */
  30522. removeChain( node ) {
  30523. const lastChain = this.chaining.pop();
  30524. if ( lastChain !== node ) {
  30525. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30526. }
  30527. }
  30528. /**
  30529. * Returns the native shader method name for a given generic name. E.g.
  30530. * the method name `textureDimensions` matches the WGSL name but must be
  30531. * resolved to `textureSize` in GLSL.
  30532. *
  30533. * @abstract
  30534. * @param {String} method - The method name to resolve.
  30535. * @return {String} The resolved method name.
  30536. */
  30537. getMethod( method ) {
  30538. return method;
  30539. }
  30540. /**
  30541. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  30542. *
  30543. * @param {Number} hash - The hash of the node.
  30544. * @return {Node} The found node.
  30545. */
  30546. getNodeFromHash( hash ) {
  30547. return this.hashNodes[ hash ];
  30548. }
  30549. /**
  30550. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  30551. *
  30552. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  30553. * @param {Node} node - The node to add.
  30554. * @return {Node} The node.
  30555. */
  30556. addFlow( shaderStage, node ) {
  30557. this.flowNodes[ shaderStage ].push( node );
  30558. return node;
  30559. }
  30560. /**
  30561. * Sets builder's context.
  30562. *
  30563. * @param {Object} context - The context to set.
  30564. */
  30565. setContext( context ) {
  30566. this.context = context;
  30567. }
  30568. /**
  30569. * Returns the builder's current context.
  30570. *
  30571. * @return {Object} The builder's current context.
  30572. */
  30573. getContext() {
  30574. return this.context;
  30575. }
  30576. /**
  30577. * Gets a context used in shader construction that can be shared across different materials.
  30578. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  30579. *
  30580. * @return {Object} The builder's current context without material.
  30581. */
  30582. getSharedContext() {
  30583. ({ ...this.context });
  30584. return this.context;
  30585. }
  30586. /**
  30587. * Sets builder's cache.
  30588. *
  30589. * @param {NodeCache} cache - The cache to set.
  30590. */
  30591. setCache( cache ) {
  30592. this.cache = cache;
  30593. }
  30594. /**
  30595. * Returns the builder's current cache.
  30596. *
  30597. * @return {NodeCache} The builder's current cache.
  30598. */
  30599. getCache() {
  30600. return this.cache;
  30601. }
  30602. /**
  30603. * Returns a cache for the given node.
  30604. *
  30605. * @param {Node} node - The node.
  30606. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  30607. * @return {NodeCache} The cache.
  30608. */
  30609. getCacheFromNode( node, parent = true ) {
  30610. const data = this.getDataFromNode( node );
  30611. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30612. return data.cache;
  30613. }
  30614. /**
  30615. * Whether the requested feature is available or not.
  30616. *
  30617. * @abstract
  30618. * @param {String} name - The requested feature.
  30619. * @return {Boolean} Whether the requested feature is supported or not.
  30620. */
  30621. isAvailable( /*name*/ ) {
  30622. return false;
  30623. }
  30624. /**
  30625. * Returns the vertexIndex input variable as a native shader string.
  30626. *
  30627. * @abstract
  30628. * @return {String} The instanceIndex shader string.
  30629. */
  30630. getVertexIndex() {
  30631. console.warn( 'Abstract function.' );
  30632. }
  30633. /**
  30634. * Returns the instanceIndex input variable as a native shader string.
  30635. *
  30636. * @abstract
  30637. * @return {String} The instanceIndex shader string.
  30638. */
  30639. getInstanceIndex() {
  30640. console.warn( 'Abstract function.' );
  30641. }
  30642. /**
  30643. * Returns the drawIndex input variable as a native shader string.
  30644. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  30645. *
  30646. * @abstract
  30647. * @return {String} The drawIndex shader string.
  30648. */
  30649. getDrawIndex() {
  30650. console.warn( 'Abstract function.' );
  30651. }
  30652. /**
  30653. * Returns the frontFacing input variable as a native shader string.
  30654. *
  30655. * @abstract
  30656. * @return {String} The frontFacing shader string.
  30657. */
  30658. getFrontFacing() {
  30659. console.warn( 'Abstract function.' );
  30660. }
  30661. /**
  30662. * Returns the fragCoord input variable as a native shader string.
  30663. *
  30664. * @abstract
  30665. * @return {String} The fragCoord shader string.
  30666. */
  30667. getFragCoord() {
  30668. console.warn( 'Abstract function.' );
  30669. }
  30670. /**
  30671. * Whether to flip texture data along its vertical axis or not. WebGL needs
  30672. * this method evaluate to `true`, WebGPU to `false`.
  30673. *
  30674. * @abstract
  30675. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  30676. */
  30677. isFlipY() {
  30678. return false;
  30679. }
  30680. /**
  30681. * Calling this method increases the usage count for the given node by one.
  30682. *
  30683. * @param {Node} node - The node to increase the usage count for.
  30684. * @return {Number} The updated usage count.
  30685. */
  30686. increaseUsage( node ) {
  30687. const nodeData = this.getDataFromNode( node );
  30688. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  30689. return nodeData.usageCount;
  30690. }
  30691. /**
  30692. * Generates a texture sample shader string for the given texture data.
  30693. *
  30694. * @abstract
  30695. * @param {Texture} texture - The texture.
  30696. * @param {String} textureProperty - The texture property name.
  30697. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30698. * @return {String} The generated shader string.
  30699. */
  30700. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  30701. console.warn( 'Abstract function.' );
  30702. }
  30703. /**
  30704. * Generates a texture LOD shader string for the given texture data.
  30705. *
  30706. * @abstract
  30707. * @param {Texture} texture - The texture.
  30708. * @param {String} textureProperty - The texture property name.
  30709. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30710. * @param {String?} depthSnippet - Snippet defining the 0-based texture array index to sample.
  30711. * @param {String} levelSnippet - Snippet defining the mip level.
  30712. * @return {String} The generated shader string.
  30713. */
  30714. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  30715. console.warn( 'Abstract function.' );
  30716. }
  30717. /**
  30718. * Generates the array declaration string.
  30719. *
  30720. * @param {String} type - The type.
  30721. * @param {Number?} [count] - The count.
  30722. * @return {String} The generated value as a shader string.
  30723. */
  30724. generateArrayDeclaration( type, count ) {
  30725. return this.getType( type ) + '[ ' + count + ' ]';
  30726. }
  30727. /**
  30728. * Generates the array shader string for the given type and value.
  30729. *
  30730. * @param {String} type - The type.
  30731. * @param {Number?} [count] - The count.
  30732. * @param {Array<Node>?} [values=null] - The default values.
  30733. * @return {String} The generated value as a shader string.
  30734. */
  30735. generateArray( type, count, values = null ) {
  30736. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  30737. for ( let i = 0; i < count; i ++ ) {
  30738. const value = values ? values[ i ] : null;
  30739. if ( value !== null ) {
  30740. snippet += value.build( this, type );
  30741. } else {
  30742. snippet += this.generateConst( type );
  30743. }
  30744. if ( i < count - 1 ) snippet += ', ';
  30745. }
  30746. snippet += ' )';
  30747. return snippet;
  30748. }
  30749. /**
  30750. * Generates the struct shader string.
  30751. *
  30752. * @param {String} type - The type.
  30753. * @param {Array<Object>} [membersLayout] - The count.
  30754. * @param {Array<Node>?} [values=null] - The default values.
  30755. * @return {String} The generated value as a shader string.
  30756. */
  30757. generateStruct( type, membersLayout, values = null ) {
  30758. const snippets = [];
  30759. for ( const member of membersLayout ) {
  30760. const { name, type } = member;
  30761. if ( values && values[ name ] && values[ name ].isNode ) {
  30762. snippets.push( values[ name ].build( this, type ) );
  30763. } else {
  30764. snippets.push( this.generateConst( type ) );
  30765. }
  30766. }
  30767. return type + '( ' + snippets.join( ', ' ) + ' )';
  30768. }
  30769. /**
  30770. * Generates the shader string for the given type and value.
  30771. *
  30772. * @param {String} type - The type.
  30773. * @param {Any?} [value=null] - The value.
  30774. * @return {String} The generated value as a shader string.
  30775. */
  30776. generateConst( type, value = null ) {
  30777. if ( value === null ) {
  30778. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  30779. else if ( type === 'bool' ) value = false;
  30780. else if ( type === 'color' ) value = new Color();
  30781. else if ( type === 'vec2' ) value = new Vector2();
  30782. else if ( type === 'vec3' ) value = new Vector3();
  30783. else if ( type === 'vec4' ) value = new Vector4();
  30784. }
  30785. if ( type === 'float' ) return toFloat( value );
  30786. if ( type === 'int' ) return `${ Math.round( value ) }`;
  30787. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  30788. if ( type === 'bool' ) return value ? 'true' : 'false';
  30789. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  30790. const typeLength = this.getTypeLength( type );
  30791. const componentType = this.getComponentType( type );
  30792. const generateConst = value => this.generateConst( componentType, value );
  30793. if ( typeLength === 2 ) {
  30794. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  30795. } else if ( typeLength === 3 ) {
  30796. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  30797. } else if ( typeLength === 4 ) {
  30798. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  30799. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  30800. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  30801. } else if ( typeLength > 4 ) {
  30802. return `${ this.getType( type ) }()`;
  30803. }
  30804. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  30805. }
  30806. /**
  30807. * It might be necessary to convert certain data types to different ones
  30808. * so this method can be used to hide the conversion.
  30809. *
  30810. * @param {String} type - The type.
  30811. * @return {String} The updated type.
  30812. */
  30813. getType( type ) {
  30814. if ( type === 'color' ) return 'vec3';
  30815. return type;
  30816. }
  30817. /**
  30818. * Whether the given attribute name is defined in the geometry or not.
  30819. *
  30820. * @param {String} name - The attribute name.
  30821. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  30822. */
  30823. hasGeometryAttribute( name ) {
  30824. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  30825. }
  30826. /**
  30827. * Returns a node attribute for the given name and type.
  30828. *
  30829. * @param {String} name - The attribute's name.
  30830. * @param {String} type - The attribute's type.
  30831. * @return {NodeAttribute} The node attribute.
  30832. */
  30833. getAttribute( name, type ) {
  30834. const attributes = this.attributes;
  30835. // find attribute
  30836. for ( const attribute of attributes ) {
  30837. if ( attribute.name === name ) {
  30838. return attribute;
  30839. }
  30840. }
  30841. // create a new if no exist
  30842. const attribute = new NodeAttribute( name, type );
  30843. attributes.push( attribute );
  30844. return attribute;
  30845. }
  30846. /**
  30847. * Returns for the given node and shader stage the property name for the shader.
  30848. *
  30849. * @param {Node} node - The node.
  30850. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30851. * @return {String} The property name.
  30852. */
  30853. getPropertyName( node/*, shaderStage*/ ) {
  30854. return node.name;
  30855. }
  30856. /**
  30857. * Whether the given type is a vector type or not.
  30858. *
  30859. * @param {String} type - The type to check.
  30860. * @return {Boolean} Whether the given type is a vector type or not.
  30861. */
  30862. isVector( type ) {
  30863. return /vec\d/.test( type );
  30864. }
  30865. /**
  30866. * Whether the given type is a matrix type or not.
  30867. *
  30868. * @param {String} type - The type to check.
  30869. * @return {Boolean} Whether the given type is a matrix type or not.
  30870. */
  30871. isMatrix( type ) {
  30872. return /mat\d/.test( type );
  30873. }
  30874. /**
  30875. * Whether the given type is a reference type or not.
  30876. *
  30877. * @param {String} type - The type to check.
  30878. * @return {Boolean} Whether the given type is a reference type or not.
  30879. */
  30880. isReference( type ) {
  30881. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  30882. }
  30883. /**
  30884. * Checks if the given texture requires a manual conversion to the working color space.
  30885. *
  30886. * @abstract
  30887. * @param {Texture} texture - The texture to check.
  30888. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  30889. */
  30890. needsToWorkingColorSpace( /*texture*/ ) {
  30891. return false;
  30892. }
  30893. /**
  30894. * Returns the component type of a given texture.
  30895. *
  30896. * @param {Texture} texture - The texture.
  30897. * @return {String} The component type.
  30898. */
  30899. getComponentTypeFromTexture( texture ) {
  30900. const type = texture.type;
  30901. if ( texture.isDataTexture ) {
  30902. if ( type === IntType ) return 'int';
  30903. if ( type === UnsignedIntType ) return 'uint';
  30904. }
  30905. return 'float';
  30906. }
  30907. /**
  30908. * Returns the element type for a given type.
  30909. *
  30910. * @param {String} type - The type.
  30911. * @return {String} The element type.
  30912. */
  30913. getElementType( type ) {
  30914. if ( type === 'mat2' ) return 'vec2';
  30915. if ( type === 'mat3' ) return 'vec3';
  30916. if ( type === 'mat4' ) return 'vec4';
  30917. return this.getComponentType( type );
  30918. }
  30919. /**
  30920. * Returns the component type for a given type.
  30921. *
  30922. * @param {String} type - The type.
  30923. * @return {String} The component type.
  30924. */
  30925. getComponentType( type ) {
  30926. type = this.getVectorType( type );
  30927. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30928. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30929. if ( componentType === null ) return null;
  30930. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30931. if ( componentType[ 1 ] === 'i' ) return 'int';
  30932. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30933. return 'float';
  30934. }
  30935. /**
  30936. * Returns the vector type for a given type.
  30937. *
  30938. * @param {String} type - The type.
  30939. * @return {String} The vector type.
  30940. */
  30941. getVectorType( type ) {
  30942. if ( type === 'color' ) return 'vec3';
  30943. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30944. return type;
  30945. }
  30946. /**
  30947. * Returns the data type for the given the length and component type.
  30948. *
  30949. * @param {Number} length - The length.
  30950. * @param {String} [componentType='float'] - The component type.
  30951. * @return {String} The type.
  30952. */
  30953. getTypeFromLength( length, componentType = 'float' ) {
  30954. if ( length === 1 ) return componentType;
  30955. let baseType = getTypeFromLength( length );
  30956. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30957. // fix edge case for mat2x2 being same size as vec4
  30958. if ( /mat2/.test( componentType ) === true ) {
  30959. baseType = baseType.replace( 'vec', 'mat' );
  30960. }
  30961. return prefix + baseType;
  30962. }
  30963. /**
  30964. * Returns the type for a given typed array.
  30965. *
  30966. * @param {TypedArray} array - The typed array.
  30967. * @return {String} The type.
  30968. */
  30969. getTypeFromArray( array ) {
  30970. return typeFromArray.get( array.constructor );
  30971. }
  30972. /**
  30973. * Returns the type for a given buffer attribute.
  30974. *
  30975. * @param {BufferAttribute} attribute - The buffer attribute.
  30976. * @return {String} The type.
  30977. */
  30978. getTypeFromAttribute( attribute ) {
  30979. let dataAttribute = attribute;
  30980. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30981. const array = dataAttribute.array;
  30982. const itemSize = attribute.itemSize;
  30983. const normalized = attribute.normalized;
  30984. let arrayType;
  30985. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30986. arrayType = this.getTypeFromArray( array );
  30987. }
  30988. return this.getTypeFromLength( itemSize, arrayType );
  30989. }
  30990. /**
  30991. * Returns the length for the given data type.
  30992. *
  30993. * @param {String} type - The data type.
  30994. * @return {Number} The length.
  30995. */
  30996. getTypeLength( type ) {
  30997. const vecType = this.getVectorType( type );
  30998. const vecNum = /vec([2-4])/.exec( vecType );
  30999. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  31000. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  31001. if ( /mat2/.test( type ) === true ) return 4;
  31002. if ( /mat3/.test( type ) === true ) return 9;
  31003. if ( /mat4/.test( type ) === true ) return 16;
  31004. return 0;
  31005. }
  31006. /**
  31007. * Returns the vector type for a given matrix type.
  31008. *
  31009. * @param {String} type - The matrix type.
  31010. * @return {String} The vector type.
  31011. */
  31012. getVectorFromMatrix( type ) {
  31013. return type.replace( 'mat', 'vec' );
  31014. }
  31015. /**
  31016. * For a given type this method changes the component type to the
  31017. * given value. E.g. `vec4` should be changed to the new component type
  31018. * `uint` which results in `uvec4`.
  31019. *
  31020. * @param {String} type - The type.
  31021. * @param {String} newComponentType - The new component type.
  31022. * @return {String} The new type.
  31023. */
  31024. changeComponentType( type, newComponentType ) {
  31025. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  31026. }
  31027. /**
  31028. * Returns the integer type pendant for the given type.
  31029. *
  31030. * @param {String} type - The type.
  31031. * @return {String} The integer type.
  31032. */
  31033. getIntegerType( type ) {
  31034. const componentType = this.getComponentType( type );
  31035. if ( componentType === 'int' || componentType === 'uint' ) return type;
  31036. return this.changeComponentType( type, 'int' );
  31037. }
  31038. /**
  31039. * Adds a stack node to the internal stack.
  31040. *
  31041. * @return {StackNode} The added stack node.
  31042. */
  31043. addStack() {
  31044. this.stack = stack( this.stack );
  31045. this.stacks.push( getCurrentStack() || this.stack );
  31046. setCurrentStack( this.stack );
  31047. return this.stack;
  31048. }
  31049. /**
  31050. * Removes the last stack node from the internal stack.
  31051. *
  31052. * @return {StackNode} The removed stack node.
  31053. */
  31054. removeStack() {
  31055. const lastStack = this.stack;
  31056. this.stack = lastStack.parent;
  31057. setCurrentStack( this.stacks.pop() );
  31058. return lastStack;
  31059. }
  31060. /**
  31061. * The builder maintains (cached) data for each node during the building process. This method
  31062. * can be used to get these data for a specific shader stage and cache.
  31063. *
  31064. * @param {Node} node - The node to get the data for.
  31065. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31066. * @param {NodeCache?} cache - An optional cache.
  31067. * @return {Object} The node data.
  31068. */
  31069. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  31070. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  31071. let nodeData = cache.getData( node );
  31072. if ( nodeData === undefined ) {
  31073. nodeData = {};
  31074. cache.setData( node, nodeData );
  31075. }
  31076. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  31077. return nodeData[ shaderStage ];
  31078. }
  31079. /**
  31080. * Returns the properties for the given node and shader stage.
  31081. *
  31082. * @param {Node} node - The node to get the properties for.
  31083. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  31084. * @return {Object} The node properties.
  31085. */
  31086. getNodeProperties( node, shaderStage = 'any' ) {
  31087. const nodeData = this.getDataFromNode( node, shaderStage );
  31088. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  31089. }
  31090. /**
  31091. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  31092. *
  31093. * @param {BufferAttributeNode} node - The buffer attribute node.
  31094. * @param {String} type - The node type.
  31095. * @return {NodeAttribute} The node attribute.
  31096. */
  31097. getBufferAttributeFromNode( node, type ) {
  31098. const nodeData = this.getDataFromNode( node );
  31099. let bufferAttribute = nodeData.bufferAttribute;
  31100. if ( bufferAttribute === undefined ) {
  31101. const index = this.uniforms.index ++;
  31102. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  31103. this.bufferAttributes.push( bufferAttribute );
  31104. nodeData.bufferAttribute = bufferAttribute;
  31105. }
  31106. return bufferAttribute;
  31107. }
  31108. /**
  31109. * Returns an instance of {@link StructType} for the given output struct node.
  31110. *
  31111. * @param {OutputStructNode} node - The output struct node.
  31112. * @param {Array<Object>} membersLayout - The output struct types.
  31113. * @param {String?} [name=null] - The name of the struct.
  31114. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31115. * @return {StructType} The struct type attribute.
  31116. */
  31117. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  31118. const nodeData = this.getDataFromNode( node, shaderStage );
  31119. let structType = nodeData.structType;
  31120. if ( structType === undefined ) {
  31121. const index = this.structs.index ++;
  31122. if ( name === null ) name = 'StructType' + index;
  31123. structType = new StructType( name, membersLayout );
  31124. this.structs[ shaderStage ].push( structType );
  31125. nodeData.structType = structType;
  31126. }
  31127. return structType;
  31128. }
  31129. /**
  31130. * Returns an instance of {@link StructType} for the given output struct node.
  31131. *
  31132. * @param {OutputStructNode} node - The output struct node.
  31133. * @param {Array<Object>} membersLayout - The output struct types.
  31134. * @return {StructType} The struct type attribute.
  31135. */
  31136. getOutputStructTypeFromNode( node, membersLayout ) {
  31137. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  31138. structType.output = true;
  31139. return structType;
  31140. }
  31141. /**
  31142. * Returns an instance of {@link NodeUniform} for the given uniform node.
  31143. *
  31144. * @param {UniformNode} node - The uniform node.
  31145. * @param {String} type - The uniform type.
  31146. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31147. * @param {String?} name - The name of the uniform.
  31148. * @return {NodeUniform} The node uniform.
  31149. */
  31150. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  31151. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31152. let nodeUniform = nodeData.uniform;
  31153. if ( nodeUniform === undefined ) {
  31154. const index = this.uniforms.index ++;
  31155. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  31156. this.uniforms[ shaderStage ].push( nodeUniform );
  31157. nodeData.uniform = nodeUniform;
  31158. }
  31159. return nodeUniform;
  31160. }
  31161. /**
  31162. * Returns the array length.
  31163. *
  31164. * @param {Node} node - The node.
  31165. * @return {Number?} The array length.
  31166. */
  31167. getArrayCount( node ) {
  31168. let count = null;
  31169. if ( node.isArrayNode ) count = node.count;
  31170. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  31171. return count;
  31172. }
  31173. /**
  31174. * Returns an instance of {@link NodeVar} for the given variable node.
  31175. *
  31176. * @param {VarNode} node - The variable node.
  31177. * @param {String?} name - The variable's name.
  31178. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  31179. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31180. * @param {Boolean} [readOnly=false] - Whether the variable is read-only or not.
  31181. *
  31182. * @return {NodeVar} The node variable.
  31183. */
  31184. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  31185. const nodeData = this.getDataFromNode( node, shaderStage );
  31186. let nodeVar = nodeData.variable;
  31187. if ( nodeVar === undefined ) {
  31188. const idNS = readOnly ? '_const' : '_var';
  31189. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  31190. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  31191. if ( name === null ) {
  31192. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  31193. this.vars[ idNS ] ++;
  31194. }
  31195. //
  31196. const count = this.getArrayCount( node );
  31197. nodeVar = new NodeVar( name, type, readOnly, count );
  31198. if ( ! readOnly ) {
  31199. vars.push( nodeVar );
  31200. }
  31201. nodeData.variable = nodeVar;
  31202. }
  31203. return nodeVar;
  31204. }
  31205. /**
  31206. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  31207. *
  31208. * @param {Node} node - The varying node.
  31209. * @return {Boolean} Returns true if deterministic.
  31210. */
  31211. isDeterministic( node ) {
  31212. if ( node.isMathNode ) {
  31213. return this.isDeterministic( node.aNode ) &&
  31214. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  31215. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  31216. } else if ( node.isOperatorNode ) {
  31217. return this.isDeterministic( node.aNode ) &&
  31218. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  31219. } else if ( node.isArrayNode ) {
  31220. if ( node.values !== null ) {
  31221. for ( const n of node.values ) {
  31222. if ( ! this.isDeterministic( n ) ) {
  31223. return false;
  31224. }
  31225. }
  31226. }
  31227. return true;
  31228. } else if ( node.isConstNode ) {
  31229. return true;
  31230. }
  31231. return false;
  31232. }
  31233. /**
  31234. * Returns an instance of {@link NodeVarying} for the given varying node.
  31235. *
  31236. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  31237. * @param {String?} name - The varying's name.
  31238. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  31239. * @return {NodeVar} The node varying.
  31240. */
  31241. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  31242. const nodeData = this.getDataFromNode( node, 'any' );
  31243. let nodeVarying = nodeData.varying;
  31244. if ( nodeVarying === undefined ) {
  31245. const varyings = this.varyings;
  31246. const index = varyings.length;
  31247. if ( name === null ) name = 'nodeVarying' + index;
  31248. nodeVarying = new NodeVarying( name, type );
  31249. varyings.push( nodeVarying );
  31250. nodeData.varying = nodeVarying;
  31251. }
  31252. return nodeVarying;
  31253. }
  31254. /**
  31255. * Returns an instance of {@link NodeCode} for the given code node.
  31256. *
  31257. * @param {CodeNode} node - The code node.
  31258. * @param {String} type - The node type.
  31259. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31260. * @return {NodeCode} The node code.
  31261. */
  31262. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31263. const nodeData = this.getDataFromNode( node );
  31264. let nodeCode = nodeData.code;
  31265. if ( nodeCode === undefined ) {
  31266. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31267. const index = codes.length;
  31268. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31269. codes.push( nodeCode );
  31270. nodeData.code = nodeCode;
  31271. }
  31272. return nodeCode;
  31273. }
  31274. /**
  31275. * Adds a code flow based on the code-block hierarchy.
  31276. * This is used so that code-blocks like If,Else create their variables locally if the Node
  31277. * is only used inside one of these conditionals in the current shader stage.
  31278. *
  31279. * @param {Node} node - The node to add.
  31280. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  31281. */
  31282. addFlowCodeHierarchy( node, nodeBlock ) {
  31283. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31284. let needsFlowCode = true;
  31285. let nodeBlockHierarchy = nodeBlock;
  31286. while ( nodeBlockHierarchy ) {
  31287. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31288. needsFlowCode = false;
  31289. break;
  31290. }
  31291. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31292. }
  31293. if ( needsFlowCode ) {
  31294. for ( const flowCode of flowCodes ) {
  31295. this.addLineFlowCode( flowCode );
  31296. }
  31297. }
  31298. }
  31299. /**
  31300. * Add a inline-code to the current flow code-block.
  31301. *
  31302. * @param {Node} node - The node to add.
  31303. * @param {String} code - The code to add.
  31304. * @param {Node} nodeBlock - Current ConditionalNode
  31305. */
  31306. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31307. const nodeData = this.getDataFromNode( node );
  31308. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31309. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31310. flowCodes.push( code );
  31311. codeBlock.set( nodeBlock, true );
  31312. }
  31313. /**
  31314. * Add a inline-code to the current flow.
  31315. *
  31316. * @param {String} code - The code to add.
  31317. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  31318. * @return {NodeBuilder} A reference to this node builder.
  31319. */
  31320. addLineFlowCode( code, node = null ) {
  31321. if ( code === '' ) return this;
  31322. if ( node !== null && this.context.nodeBlock ) {
  31323. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31324. }
  31325. code = this.tab + code;
  31326. if ( ! /;\s*$/.test( code ) ) {
  31327. code = code + ';\n';
  31328. }
  31329. this.flow.code += code;
  31330. return this;
  31331. }
  31332. /**
  31333. * Adds a code to the current code flow.
  31334. *
  31335. * @param {String} code - Shader code.
  31336. * @return {NodeBuilder} A reference to this node builder.
  31337. */
  31338. addFlowCode( code ) {
  31339. this.flow.code += code;
  31340. return this;
  31341. }
  31342. /**
  31343. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  31344. * Typically used in codes with If,Else.
  31345. *
  31346. * @return {NodeBuilder} A reference to this node builder.
  31347. */
  31348. addFlowTab() {
  31349. this.tab += '\t';
  31350. return this;
  31351. }
  31352. /**
  31353. * Removes a tab.
  31354. *
  31355. * @return {NodeBuilder} A reference to this node builder.
  31356. */
  31357. removeFlowTab() {
  31358. this.tab = this.tab.slice( 0, - 1 );
  31359. return this;
  31360. }
  31361. /**
  31362. * Gets the current flow data based on a Node.
  31363. *
  31364. * @param {Node} node - Node that the flow was started.
  31365. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31366. * @return {Object} The flow data.
  31367. */
  31368. getFlowData( node/*, shaderStage*/ ) {
  31369. return this.flowsData.get( node );
  31370. }
  31371. /**
  31372. * Executes the node flow based on a root node to generate the final shader code.
  31373. *
  31374. * @param {Node} node - The node to execute.
  31375. * @return {Object} The code flow.
  31376. */
  31377. flowNode( node ) {
  31378. const output = node.getNodeType( this );
  31379. const flowData = this.flowChildNode( node, output );
  31380. this.flowsData.set( node, flowData );
  31381. return flowData;
  31382. }
  31383. /**
  31384. * Returns the native shader operator name for a given generic name.
  31385. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31386. *
  31387. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  31388. * @return {FunctionNode} The build function node.
  31389. */
  31390. buildFunctionNode( shaderNode ) {
  31391. const fn = new FunctionNode();
  31392. const previous = this.currentFunctionNode;
  31393. this.currentFunctionNode = fn;
  31394. fn.code = this.buildFunctionCode( shaderNode );
  31395. this.currentFunctionNode = previous;
  31396. return fn;
  31397. }
  31398. /**
  31399. * Generates a code flow based on a TSL function: Fn().
  31400. *
  31401. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  31402. * @return {Object}
  31403. */
  31404. flowShaderNode( shaderNode ) {
  31405. const layout = shaderNode.layout;
  31406. const inputs = {
  31407. [ Symbol.iterator ]() {
  31408. let index = 0;
  31409. const values = Object.values( this );
  31410. return {
  31411. next: () => ( {
  31412. value: values[ index ],
  31413. done: index ++ >= values.length
  31414. } )
  31415. };
  31416. }
  31417. };
  31418. for ( const input of layout.inputs ) {
  31419. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31420. }
  31421. //
  31422. shaderNode.layout = null;
  31423. const callNode = shaderNode.call( inputs );
  31424. const flowData = this.flowStagesNode( callNode, layout.type );
  31425. shaderNode.layout = layout;
  31426. return flowData;
  31427. }
  31428. /**
  31429. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  31430. *
  31431. * @param {Node} node - The node to execute.
  31432. * @param {String?} output - Expected output type. For example 'vec3'.
  31433. * @return {Object}
  31434. */
  31435. flowStagesNode( node, output = null ) {
  31436. const previousFlow = this.flow;
  31437. const previousVars = this.vars;
  31438. const previousCache = this.cache;
  31439. const previousBuildStage = this.buildStage;
  31440. const previousStack = this.stack;
  31441. const flow = {
  31442. code: ''
  31443. };
  31444. this.flow = flow;
  31445. this.vars = {};
  31446. this.cache = new NodeCache();
  31447. this.stack = stack();
  31448. for ( const buildStage of defaultBuildStages ) {
  31449. this.setBuildStage( buildStage );
  31450. flow.result = node.build( this, output );
  31451. }
  31452. flow.vars = this.getVars( this.shaderStage );
  31453. this.flow = previousFlow;
  31454. this.vars = previousVars;
  31455. this.cache = previousCache;
  31456. this.stack = previousStack;
  31457. this.setBuildStage( previousBuildStage );
  31458. return flow;
  31459. }
  31460. /**
  31461. * Returns the native shader operator name for a given generic name.
  31462. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  31463. *
  31464. * @abstract
  31465. * @param {String} op - The operator name to resolve.
  31466. * @return {String} The resolved operator name.
  31467. */
  31468. getFunctionOperator( /* op */ ) {
  31469. return null;
  31470. }
  31471. /**
  31472. * Generates a code flow based on a child Node.
  31473. *
  31474. * @param {Node} node - The node to execute.
  31475. * @param {String?} output - Expected output type. For example 'vec3'.
  31476. * @return {Object} The code flow.
  31477. */
  31478. flowChildNode( node, output = null ) {
  31479. const previousFlow = this.flow;
  31480. const flow = {
  31481. code: ''
  31482. };
  31483. this.flow = flow;
  31484. flow.result = node.build( this, output );
  31485. this.flow = previousFlow;
  31486. return flow;
  31487. }
  31488. /**
  31489. * Executes a flow of code in a different stage.
  31490. *
  31491. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  31492. * return the value in fragment-stage even if it is being executed in an input fragment.
  31493. *
  31494. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31495. * @param {Node} node - The node to execute.
  31496. * @param {String?} output - Expected output type. For example 'vec3'.
  31497. * @param {String?} propertyName - The property name to assign the result.
  31498. * @return {Object}
  31499. */
  31500. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31501. const previousShaderStage = this.shaderStage;
  31502. this.setShaderStage( shaderStage );
  31503. const flowData = this.flowChildNode( node, output );
  31504. if ( propertyName !== null ) {
  31505. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31506. }
  31507. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31508. this.setShaderStage( previousShaderStage );
  31509. return flowData;
  31510. }
  31511. /**
  31512. * Returns an array holding all node attributes of this node builder.
  31513. *
  31514. * @return {Array<NodeAttribute>} The node attributes of this builder.
  31515. */
  31516. getAttributesArray() {
  31517. return this.attributes.concat( this.bufferAttributes );
  31518. }
  31519. /**
  31520. * Returns the attribute definitions as a shader string for the given shader stage.
  31521. *
  31522. * @abstract
  31523. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31524. * @return {String} The attribute code section.
  31525. */
  31526. getAttributes( /*shaderStage*/ ) {
  31527. console.warn( 'Abstract function.' );
  31528. }
  31529. /**
  31530. * Returns the varying definitions as a shader string for the given shader stage.
  31531. *
  31532. * @abstract
  31533. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31534. * @return {String} The varying code section.
  31535. */
  31536. getVaryings( /*shaderStage*/ ) {
  31537. console.warn( 'Abstract function.' );
  31538. }
  31539. /**
  31540. * Returns a single variable definition as a shader string for the given variable type and name.
  31541. *
  31542. * @param {String} type - The variable's type.
  31543. * @param {String} name - The variable's name.
  31544. * @param {Number?} [count=null] - The array length.
  31545. * @return {String} The shader string.
  31546. */
  31547. getVar( type, name, count = null ) {
  31548. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  31549. }
  31550. /**
  31551. * Returns the variable definitions as a shader string for the given shader stage.
  31552. *
  31553. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31554. * @return {String} The variable code section.
  31555. */
  31556. getVars( shaderStage ) {
  31557. let snippet = '';
  31558. const vars = this.vars[ shaderStage ];
  31559. if ( vars !== undefined ) {
  31560. for ( const variable of vars ) {
  31561. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31562. }
  31563. }
  31564. return snippet;
  31565. }
  31566. /**
  31567. * Returns the uniform definitions as a shader string for the given shader stage.
  31568. *
  31569. * @abstract
  31570. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31571. * @return {String} The uniform code section.
  31572. */
  31573. getUniforms( /*shaderStage*/ ) {
  31574. console.warn( 'Abstract function.' );
  31575. }
  31576. /**
  31577. * Returns the native code definitions as a shader string for the given shader stage.
  31578. *
  31579. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31580. * @return {String} The native code section.
  31581. */
  31582. getCodes( shaderStage ) {
  31583. const codes = this.codes[ shaderStage ];
  31584. let code = '';
  31585. if ( codes !== undefined ) {
  31586. for ( const nodeCode of codes ) {
  31587. code += nodeCode.code + '\n';
  31588. }
  31589. }
  31590. return code;
  31591. }
  31592. /**
  31593. * Returns the hash of this node builder.
  31594. *
  31595. * @return {String} The hash.
  31596. */
  31597. getHash() {
  31598. return this.vertexShader + this.fragmentShader + this.computeShader;
  31599. }
  31600. /**
  31601. * Sets the current shader stage.
  31602. *
  31603. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  31604. */
  31605. setShaderStage( shaderStage ) {
  31606. this.shaderStage = shaderStage;
  31607. }
  31608. /**
  31609. * Returns the current shader stage.
  31610. *
  31611. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  31612. */
  31613. getShaderStage() {
  31614. return this.shaderStage;
  31615. }
  31616. /**
  31617. * Sets the current build stage.
  31618. *
  31619. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  31620. */
  31621. setBuildStage( buildStage ) {
  31622. this.buildStage = buildStage;
  31623. }
  31624. /**
  31625. * Returns the current build stage.
  31626. *
  31627. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  31628. */
  31629. getBuildStage() {
  31630. return this.buildStage;
  31631. }
  31632. /**
  31633. * Controls the code build of the shader stages.
  31634. *
  31635. * @abstract
  31636. */
  31637. buildCode() {
  31638. console.warn( 'Abstract function.' );
  31639. }
  31640. /**
  31641. * Central build method which controls the build for the given object.
  31642. *
  31643. * @return {NodeBuilder} A reference to this node builder.
  31644. */
  31645. build() {
  31646. const { object, material, renderer } = this;
  31647. if ( material !== null ) {
  31648. let nodeMaterial = renderer.library.fromMaterial( material );
  31649. if ( nodeMaterial === null ) {
  31650. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31651. nodeMaterial = new NodeMaterial();
  31652. }
  31653. nodeMaterial.build( this );
  31654. } else {
  31655. this.addFlow( 'compute', object );
  31656. }
  31657. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31658. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31659. // generate() -> stage 3: generate shader
  31660. for ( const buildStage of defaultBuildStages ) {
  31661. this.setBuildStage( buildStage );
  31662. if ( this.context.vertex && this.context.vertex.isNode ) {
  31663. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31664. }
  31665. for ( const shaderStage of shaderStages ) {
  31666. this.setShaderStage( shaderStage );
  31667. const flowNodes = this.flowNodes[ shaderStage ];
  31668. for ( const node of flowNodes ) {
  31669. if ( buildStage === 'generate' ) {
  31670. this.flowNode( node );
  31671. } else {
  31672. node.build( this );
  31673. }
  31674. }
  31675. }
  31676. }
  31677. this.setBuildStage( null );
  31678. this.setShaderStage( null );
  31679. // stage 4: build code for a specific output
  31680. this.buildCode();
  31681. this.buildUpdateNodes();
  31682. return this;
  31683. }
  31684. /**
  31685. * Returns a uniform representation which is later used for UBO generation and rendering.
  31686. *
  31687. * @param {NodeUniform} uniformNode - The uniform node.
  31688. * @param {String} type - The requested type.
  31689. * @return {Uniform} The uniform.
  31690. */
  31691. getNodeUniform( uniformNode, type ) {
  31692. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31693. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31694. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31695. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31696. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31697. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  31698. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31699. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31700. throw new Error( `Uniform "${type}" not declared.` );
  31701. }
  31702. /**
  31703. * Formats the given shader snippet from a given type into another one. E.g.
  31704. * this method might be used to convert a simple float string `"1.0"` into a
  31705. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  31706. *
  31707. * @param {String} snippet - The shader snippet.
  31708. * @param {String} fromType - The source type.
  31709. * @param {String} toType - The target type.
  31710. * @return {String} The updated shader string.
  31711. */
  31712. format( snippet, fromType, toType ) {
  31713. fromType = this.getVectorType( fromType );
  31714. toType = this.getVectorType( toType );
  31715. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31716. return snippet;
  31717. }
  31718. const fromTypeLength = this.getTypeLength( fromType );
  31719. const toTypeLength = this.getTypeLength( toType );
  31720. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31721. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31722. }
  31723. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31724. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31725. }
  31726. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31727. // @TODO: ignore for now
  31728. return snippet;
  31729. }
  31730. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31731. // @TODO: ignore for now
  31732. return snippet;
  31733. }
  31734. if ( fromTypeLength === toTypeLength ) {
  31735. return `${ this.getType( toType ) }( ${ snippet } )`;
  31736. }
  31737. if ( fromTypeLength > toTypeLength ) {
  31738. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31739. }
  31740. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31741. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31742. }
  31743. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31744. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31745. }
  31746. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31747. // convert a number value to vector type, e.g:
  31748. // vec3( 1u ) -> vec3( float( 1u ) )
  31749. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31750. }
  31751. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31752. }
  31753. /**
  31754. * Returns a signature with the engine's current revision.
  31755. *
  31756. * @return {String} The signature.
  31757. */
  31758. getSignature() {
  31759. return `// Three.js r${ REVISION } - Node System\n`;
  31760. }
  31761. // Deprecated
  31762. /**
  31763. * @function
  31764. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  31765. *
  31766. * @param {String} [type='NodeMaterial'] - The node material type.
  31767. * @throws {Error}
  31768. */
  31769. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31770. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31771. }
  31772. }
  31773. /**
  31774. * Management class for updating nodes. The module tracks metrics like
  31775. * the elapsed time, delta time, the render and frame ID to correctly
  31776. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  31777. * and {@link Node#updateAfter} depending on the node's configuration.
  31778. */
  31779. class NodeFrame {
  31780. /**
  31781. * Constructs a new node fame.
  31782. */
  31783. constructor() {
  31784. /**
  31785. * The elapsed time in seconds.
  31786. *
  31787. * @type {Number}
  31788. * @default 0
  31789. */
  31790. this.time = 0;
  31791. /**
  31792. * The delta time in seconds.
  31793. *
  31794. * @type {Number}
  31795. * @default 0
  31796. */
  31797. this.deltaTime = 0;
  31798. /**
  31799. * The frame ID.
  31800. *
  31801. * @type {Number}
  31802. * @default 0
  31803. */
  31804. this.frameId = 0;
  31805. /**
  31806. * The render ID.
  31807. *
  31808. * @type {Number}
  31809. * @default 0
  31810. */
  31811. this.renderId = 0;
  31812. /**
  31813. * Used to control the {@link Node#update} call.
  31814. *
  31815. * @type {WeakMap<Node, Object>}
  31816. */
  31817. this.updateMap = new WeakMap();
  31818. /**
  31819. * Used to control the {@link Node#updateBefore} call.
  31820. *
  31821. * @type {WeakMap<Node, Object>}
  31822. */
  31823. this.updateBeforeMap = new WeakMap();
  31824. /**
  31825. * Used to control the {@link Node#updateAfter} call.
  31826. *
  31827. * @type {WeakMap<Node, Object>}
  31828. */
  31829. this.updateAfterMap = new WeakMap();
  31830. /**
  31831. * A reference to the current renderer.
  31832. *
  31833. * @type {Renderer?}
  31834. * @default null
  31835. */
  31836. this.renderer = null;
  31837. /**
  31838. * A reference to the current material.
  31839. *
  31840. * @type {Material?}
  31841. * @default null
  31842. */
  31843. this.material = null;
  31844. /**
  31845. * A reference to the current camera.
  31846. *
  31847. * @type {Camera?}
  31848. * @default null
  31849. */
  31850. this.camera = null;
  31851. /**
  31852. * A reference to the current 3D object.
  31853. *
  31854. * @type {Object3D?}
  31855. * @default null
  31856. */
  31857. this.object = null;
  31858. /**
  31859. * A reference to the current scene.
  31860. *
  31861. * @type {Scene?}
  31862. * @default null
  31863. */
  31864. this.scene = null;
  31865. }
  31866. /**
  31867. * Returns a dictionary for a given node and update map which
  31868. * is used to correctly call node update methods per frame or render.
  31869. *
  31870. * @private
  31871. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  31872. * @param {Node} nodeRef - The reference to the current node.
  31873. * @return {Object<String,WeakMap>} The dictionary.
  31874. */
  31875. _getMaps( referenceMap, nodeRef ) {
  31876. let maps = referenceMap.get( nodeRef );
  31877. if ( maps === undefined ) {
  31878. maps = {
  31879. renderMap: new WeakMap(),
  31880. frameMap: new WeakMap()
  31881. };
  31882. referenceMap.set( nodeRef, maps );
  31883. }
  31884. return maps;
  31885. }
  31886. /**
  31887. * This method executes the {@link Node#updateBefore} for the given node.
  31888. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  31889. * is only executed once per frame, render or object depending on the update
  31890. * type.
  31891. *
  31892. * @param {Node} node - The node that should be updated.
  31893. */
  31894. updateBeforeNode( node ) {
  31895. const updateType = node.getUpdateBeforeType();
  31896. const reference = node.updateReference( this );
  31897. if ( updateType === NodeUpdateType.FRAME ) {
  31898. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31899. if ( frameMap.get( reference ) !== this.frameId ) {
  31900. if ( node.updateBefore( this ) !== false ) {
  31901. frameMap.set( reference, this.frameId );
  31902. }
  31903. }
  31904. } else if ( updateType === NodeUpdateType.RENDER ) {
  31905. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31906. if ( renderMap.get( reference ) !== this.renderId ) {
  31907. if ( node.updateBefore( this ) !== false ) {
  31908. renderMap.set( reference, this.renderId );
  31909. }
  31910. }
  31911. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31912. node.updateBefore( this );
  31913. }
  31914. }
  31915. /**
  31916. * This method executes the {@link Node#updateAfter} for the given node.
  31917. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  31918. * is only executed once per frame, render or object depending on the update
  31919. * type.
  31920. *
  31921. * @param {Node} node - The node that should be updated.
  31922. */
  31923. updateAfterNode( node ) {
  31924. const updateType = node.getUpdateAfterType();
  31925. const reference = node.updateReference( this );
  31926. if ( updateType === NodeUpdateType.FRAME ) {
  31927. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31928. if ( frameMap.get( reference ) !== this.frameId ) {
  31929. if ( node.updateAfter( this ) !== false ) {
  31930. frameMap.set( reference, this.frameId );
  31931. }
  31932. }
  31933. } else if ( updateType === NodeUpdateType.RENDER ) {
  31934. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31935. if ( renderMap.get( reference ) !== this.renderId ) {
  31936. if ( node.updateAfter( this ) !== false ) {
  31937. renderMap.set( reference, this.renderId );
  31938. }
  31939. }
  31940. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31941. node.updateAfter( this );
  31942. }
  31943. }
  31944. /**
  31945. * This method executes the {@link Node#update} for the given node.
  31946. * It makes sure {@link Node#updateType} is honored meaning the update
  31947. * is only executed once per frame, render or object depending on the update
  31948. * type.
  31949. *
  31950. * @param {Node} node - The node that should be updated.
  31951. */
  31952. updateNode( node ) {
  31953. const updateType = node.getUpdateType();
  31954. const reference = node.updateReference( this );
  31955. if ( updateType === NodeUpdateType.FRAME ) {
  31956. const { frameMap } = this._getMaps( this.updateMap, reference );
  31957. if ( frameMap.get( reference ) !== this.frameId ) {
  31958. if ( node.update( this ) !== false ) {
  31959. frameMap.set( reference, this.frameId );
  31960. }
  31961. }
  31962. } else if ( updateType === NodeUpdateType.RENDER ) {
  31963. const { renderMap } = this._getMaps( this.updateMap, reference );
  31964. if ( renderMap.get( reference ) !== this.renderId ) {
  31965. if ( node.update( this ) !== false ) {
  31966. renderMap.set( reference, this.renderId );
  31967. }
  31968. }
  31969. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31970. node.update( this );
  31971. }
  31972. }
  31973. /**
  31974. * Updates the internal state of the node frame. This method is
  31975. * called by the renderer in its internal animation loop.
  31976. */
  31977. update() {
  31978. this.frameId ++;
  31979. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31980. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31981. this.lastTime = performance.now();
  31982. this.time += this.deltaTime;
  31983. }
  31984. }
  31985. /**
  31986. * Describes the input of a {@link NodeFunction}.
  31987. */
  31988. class NodeFunctionInput {
  31989. /**
  31990. * Constructs a new node function input.
  31991. *
  31992. * @param {String} type - The input type.
  31993. * @param {String} name - The input name.
  31994. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31995. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31996. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31997. */
  31998. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31999. /**
  32000. * The input type.
  32001. *
  32002. * @type {String}
  32003. */
  32004. this.type = type;
  32005. /**
  32006. * The input name.
  32007. *
  32008. * @type {String}
  32009. */
  32010. this.name = name;
  32011. /**
  32012. * If the input is an Array, count will be the length.
  32013. *
  32014. * @type {Number?}
  32015. * @default null
  32016. */
  32017. this.count = count;
  32018. /**
  32019. *The parameter qualifier (only relevant for GLSL).
  32020. *
  32021. * @type {('in'|'out'|'inout')}
  32022. * @default ''
  32023. */
  32024. this.qualifier = qualifier;
  32025. /**
  32026. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  32027. *
  32028. * @type {Boolean}
  32029. * @default false
  32030. */
  32031. this.isConst = isConst;
  32032. }
  32033. }
  32034. NodeFunctionInput.isNodeFunctionInput = true;
  32035. /**
  32036. * Module for representing directional lights as nodes.
  32037. *
  32038. * @augments AnalyticLightNode
  32039. */
  32040. class DirectionalLightNode extends AnalyticLightNode {
  32041. static get type() {
  32042. return 'DirectionalLightNode';
  32043. }
  32044. /**
  32045. * Constructs a new directional light node.
  32046. *
  32047. * @param {DirectionalLight?} [light=null] - The directional light source.
  32048. */
  32049. constructor( light = null ) {
  32050. super( light );
  32051. }
  32052. setup( builder ) {
  32053. super.setup( builder );
  32054. const lightingModel = builder.context.lightingModel;
  32055. const lightColor = this.colorNode;
  32056. const lightDirection = lightTargetDirection( this.light );
  32057. const reflectedLight = builder.context.reflectedLight;
  32058. lightingModel.direct( {
  32059. lightDirection,
  32060. lightColor,
  32061. reflectedLight
  32062. }, builder.stack, builder );
  32063. }
  32064. }
  32065. const _matrix41 = /*@__PURE__*/ new Matrix4();
  32066. const _matrix42 = /*@__PURE__*/ new Matrix4();
  32067. let _ltcLib = null;
  32068. /**
  32069. * Module for representing rect area lights as nodes.
  32070. *
  32071. * @augments AnalyticLightNode
  32072. */
  32073. class RectAreaLightNode extends AnalyticLightNode {
  32074. static get type() {
  32075. return 'RectAreaLightNode';
  32076. }
  32077. /**
  32078. * Constructs a new rect area light node.
  32079. *
  32080. * @param {RectAreaLight?} [light=null] - The rect area light source.
  32081. */
  32082. constructor( light = null ) {
  32083. super( light );
  32084. /**
  32085. * Uniform node representing the half height of the are light.
  32086. *
  32087. * @type {UniformNode<vec3>}
  32088. */
  32089. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  32090. /**
  32091. * Uniform node representing the half width of the are light.
  32092. *
  32093. * @type {UniformNode<vec3>}
  32094. */
  32095. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  32096. /**
  32097. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  32098. * relies on `viewMatrix` which might vary per render call.
  32099. *
  32100. * @type {String}
  32101. * @default 'render'
  32102. */
  32103. this.updateType = NodeUpdateType.RENDER;
  32104. }
  32105. /**
  32106. * Overwritten to updated rect area light specific uniforms.
  32107. *
  32108. * @param {NodeFrame} frame - A reference to the current node frame.
  32109. */
  32110. update( frame ) {
  32111. super.update( frame );
  32112. const { light } = this;
  32113. const viewMatrix = frame.camera.matrixWorldInverse;
  32114. _matrix42.identity();
  32115. _matrix41.copy( light.matrixWorld );
  32116. _matrix41.premultiply( viewMatrix );
  32117. _matrix42.extractRotation( _matrix41 );
  32118. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  32119. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  32120. this.halfWidth.value.applyMatrix4( _matrix42 );
  32121. this.halfHeight.value.applyMatrix4( _matrix42 );
  32122. }
  32123. setup( builder ) {
  32124. super.setup( builder );
  32125. let ltc_1, ltc_2;
  32126. if ( builder.isAvailable( 'float32Filterable' ) ) {
  32127. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  32128. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  32129. } else {
  32130. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  32131. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  32132. }
  32133. const { colorNode, light } = this;
  32134. const lightingModel = builder.context.lightingModel;
  32135. const lightPosition = lightViewPosition( light );
  32136. const reflectedLight = builder.context.reflectedLight;
  32137. lightingModel.directRectArea( {
  32138. lightColor: colorNode,
  32139. lightPosition,
  32140. halfWidth: this.halfWidth,
  32141. halfHeight: this.halfHeight,
  32142. reflectedLight,
  32143. ltc_1,
  32144. ltc_2
  32145. }, builder.stack, builder );
  32146. }
  32147. /**
  32148. * Used to configure the internal BRDF approximation texture data.
  32149. *
  32150. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  32151. */
  32152. static setLTC( ltc ) {
  32153. _ltcLib = ltc;
  32154. }
  32155. }
  32156. /**
  32157. * Module for representing spot lights as nodes.
  32158. *
  32159. * @augments AnalyticLightNode
  32160. */
  32161. class SpotLightNode extends AnalyticLightNode {
  32162. static get type() {
  32163. return 'SpotLightNode';
  32164. }
  32165. /**
  32166. * Constructs a new spot light node.
  32167. *
  32168. * @param {SpotLight?} [light=null] - The spot light source.
  32169. */
  32170. constructor( light = null ) {
  32171. super( light );
  32172. /**
  32173. * Uniform node representing the cone cosine.
  32174. *
  32175. * @type {UniformNode<float>}
  32176. */
  32177. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  32178. /**
  32179. * Uniform node representing the penumbra cosine.
  32180. *
  32181. * @type {UniformNode<float>}
  32182. */
  32183. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  32184. /**
  32185. * Uniform node representing the cutoff distance.
  32186. *
  32187. * @type {UniformNode<float>}
  32188. */
  32189. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32190. /**
  32191. * Uniform node representing the decay exponent.
  32192. *
  32193. * @type {UniformNode<float>}
  32194. */
  32195. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  32196. }
  32197. /**
  32198. * Overwritten to updated spot light specific uniforms.
  32199. *
  32200. * @param {NodeFrame} frame - A reference to the current node frame.
  32201. */
  32202. update( frame ) {
  32203. super.update( frame );
  32204. const { light } = this;
  32205. this.coneCosNode.value = Math.cos( light.angle );
  32206. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  32207. this.cutoffDistanceNode.value = light.distance;
  32208. this.decayExponentNode.value = light.decay;
  32209. }
  32210. /**
  32211. * Computes the spot attenuation for the given angle.
  32212. *
  32213. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32214. * @return {Node<float>} The spot attenuation.
  32215. */
  32216. getSpotAttenuation( angleCosine ) {
  32217. const { coneCosNode, penumbraCosNode } = this;
  32218. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  32219. }
  32220. setup( builder ) {
  32221. super.setup( builder );
  32222. const lightingModel = builder.context.lightingModel;
  32223. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32224. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  32225. const lightDirection = lVector.normalize();
  32226. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  32227. const spotAttenuation = this.getSpotAttenuation( angleCos );
  32228. const lightDistance = lVector.length();
  32229. const lightAttenuation = getDistanceAttenuation( {
  32230. lightDistance,
  32231. cutoffDistance: cutoffDistanceNode,
  32232. decayExponent: decayExponentNode
  32233. } );
  32234. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  32235. if ( light.map ) {
  32236. const spotLightCoord = lightProjectionUV( light );
  32237. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  32238. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  32239. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  32240. }
  32241. const reflectedLight = builder.context.reflectedLight;
  32242. lightingModel.direct( {
  32243. lightDirection,
  32244. lightColor,
  32245. reflectedLight
  32246. }, builder.stack, builder );
  32247. }
  32248. }
  32249. /**
  32250. * An IES version of the default spot light node.
  32251. *
  32252. * @augments SpotLightNode
  32253. */
  32254. class IESSpotLightNode extends SpotLightNode {
  32255. static get type() {
  32256. return 'IESSpotLightNode';
  32257. }
  32258. /**
  32259. * Overwrites the default implementation to compute an IES conform spot attenuation.
  32260. *
  32261. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32262. * @return {Node<float>} The spot attenuation.
  32263. */
  32264. getSpotAttenuation( angleCosine ) {
  32265. const iesMap = this.light.iesMap;
  32266. let spotAttenuation = null;
  32267. if ( iesMap && iesMap.isTexture === true ) {
  32268. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32269. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32270. } else {
  32271. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32272. }
  32273. return spotAttenuation;
  32274. }
  32275. }
  32276. /**
  32277. * Module for representing ambient lights as nodes.
  32278. *
  32279. * @augments AnalyticLightNode
  32280. */
  32281. class AmbientLightNode extends AnalyticLightNode {
  32282. static get type() {
  32283. return 'AmbientLightNode';
  32284. }
  32285. /**
  32286. * Constructs a new ambient light node.
  32287. *
  32288. * @param {AmbientLight?} [light=null] - The ambient light source.
  32289. */
  32290. constructor( light = null ) {
  32291. super( light );
  32292. }
  32293. setup( { context } ) {
  32294. context.irradiance.addAssign( this.colorNode );
  32295. }
  32296. }
  32297. /**
  32298. * Module for representing hemisphere lights as nodes.
  32299. *
  32300. * @augments AnalyticLightNode
  32301. */
  32302. class HemisphereLightNode extends AnalyticLightNode {
  32303. static get type() {
  32304. return 'HemisphereLightNode';
  32305. }
  32306. /**
  32307. * Constructs a new hemisphere light node.
  32308. *
  32309. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  32310. */
  32311. constructor( light = null ) {
  32312. super( light );
  32313. /**
  32314. * Uniform node representing the light's position.
  32315. *
  32316. * @type {UniformNode<vec3>}
  32317. */
  32318. this.lightPositionNode = lightPosition( light );
  32319. /**
  32320. * A node representing the light's direction.
  32321. *
  32322. * @type {Node<vec3>}
  32323. */
  32324. this.lightDirectionNode = this.lightPositionNode.normalize();
  32325. /**
  32326. * Uniform node representing the light's ground color.
  32327. *
  32328. * @type {UniformNode<vec3>}
  32329. */
  32330. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  32331. }
  32332. /**
  32333. * Overwritten to updated hemisphere light specific uniforms.
  32334. *
  32335. * @param {NodeFrame} frame - A reference to the current node frame.
  32336. */
  32337. update( frame ) {
  32338. const { light } = this;
  32339. super.update( frame );
  32340. this.lightPositionNode.object3d = light;
  32341. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32342. }
  32343. setup( builder ) {
  32344. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32345. const dotNL = normalView.dot( lightDirectionNode );
  32346. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32347. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32348. builder.context.irradiance.addAssign( irradiance );
  32349. }
  32350. }
  32351. /**
  32352. * Module for representing light probes as nodes.
  32353. *
  32354. * @augments AnalyticLightNode
  32355. */
  32356. class LightProbeNode extends AnalyticLightNode {
  32357. static get type() {
  32358. return 'LightProbeNode';
  32359. }
  32360. /**
  32361. * Constructs a new light probe node.
  32362. *
  32363. * @param {LightProbe?} [light=null] - The light probe.
  32364. */
  32365. constructor( light = null ) {
  32366. super( light );
  32367. const array = [];
  32368. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  32369. /**
  32370. * Light probe represented as a uniform of spherical harmonics.
  32371. *
  32372. * @type {UniformArrayNode}
  32373. */
  32374. this.lightProbe = uniformArray( array );
  32375. }
  32376. /**
  32377. * Overwritten to updated light probe specific uniforms.
  32378. *
  32379. * @param {NodeFrame} frame - A reference to the current node frame.
  32380. */
  32381. update( frame ) {
  32382. const { light } = this;
  32383. super.update( frame );
  32384. //
  32385. for ( let i = 0; i < 9; i ++ ) {
  32386. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  32387. }
  32388. }
  32389. setup( builder ) {
  32390. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  32391. builder.context.irradiance.addAssign( irradiance );
  32392. }
  32393. }
  32394. /**
  32395. * Base class for node parsers. A derived parser must be implemented
  32396. * for each supported native shader language.
  32397. */
  32398. class NodeParser {
  32399. /**
  32400. * The method parses the given native code an returns a node function.
  32401. *
  32402. * @abstract
  32403. * @param {String} source - The native shader code.
  32404. * @return {NodeFunction} A node function.
  32405. */
  32406. parseFunction( /*source*/ ) {
  32407. console.warn( 'Abstract function.' );
  32408. }
  32409. }
  32410. /**
  32411. * Base class for node functions. A derived module must be implemented
  32412. * for each supported native shader language. Similar to other `Node*` modules,
  32413. * this class is only relevant during the building process and not used
  32414. * in user-level code.
  32415. */
  32416. class NodeFunction {
  32417. /**
  32418. * Constructs a new node function.
  32419. *
  32420. * @param {String} type - The node type. This type is the return type of the node function.
  32421. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  32422. * @param {String} [name=''] - The function's name.
  32423. * @param {String} [precision=''] - The precision qualifier.
  32424. */
  32425. constructor( type, inputs, name = '', precision = '' ) {
  32426. /**
  32427. * The node type. This type is the return type of the node function.
  32428. *
  32429. * @type {String}
  32430. */
  32431. this.type = type;
  32432. /**
  32433. * The function's inputs.
  32434. *
  32435. * @type {Array<NodeFunctionInput>}
  32436. */
  32437. this.inputs = inputs;
  32438. /**
  32439. * The name of the uniform.
  32440. *
  32441. * @type {String}
  32442. * @default ''
  32443. */
  32444. this.name = name;
  32445. /**
  32446. * The precision qualifier.
  32447. *
  32448. * @type {String}
  32449. * @default ''
  32450. */
  32451. this.precision = precision;
  32452. }
  32453. /**
  32454. * This method returns the native code of the node function.
  32455. *
  32456. * @abstract
  32457. * @param {String} name - The function's name.
  32458. * @return {String} A shader code.
  32459. */
  32460. getCode( /*name = this.name*/ ) {
  32461. console.warn( 'Abstract function.' );
  32462. }
  32463. }
  32464. NodeFunction.isNodeFunction = true;
  32465. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  32466. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  32467. const pragmaMain = '#pragma main';
  32468. const parse$1 = ( source ) => {
  32469. source = source.trim();
  32470. const pragmaMainIndex = source.indexOf( pragmaMain );
  32471. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  32472. const declaration = mainCode.match( declarationRegexp$1 );
  32473. if ( declaration !== null && declaration.length === 5 ) {
  32474. // tokenizer
  32475. const inputsCode = declaration[ 4 ];
  32476. const propsMatches = [];
  32477. let nameMatch = null;
  32478. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  32479. propsMatches.push( nameMatch );
  32480. }
  32481. // parser
  32482. const inputs = [];
  32483. let i = 0;
  32484. while ( i < propsMatches.length ) {
  32485. const isConst = propsMatches[ i ][ 0 ] === 'const';
  32486. if ( isConst === true ) {
  32487. i ++;
  32488. }
  32489. let qualifier = propsMatches[ i ][ 0 ];
  32490. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  32491. i ++;
  32492. } else {
  32493. qualifier = '';
  32494. }
  32495. const type = propsMatches[ i ++ ][ 0 ];
  32496. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  32497. if ( Number.isNaN( count ) === false ) i ++;
  32498. else count = null;
  32499. const name = propsMatches[ i ++ ][ 0 ];
  32500. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  32501. }
  32502. //
  32503. const blockCode = mainCode.substring( declaration[ 0 ].length );
  32504. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  32505. const type = declaration[ 2 ];
  32506. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  32507. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  32508. return {
  32509. type,
  32510. inputs,
  32511. name,
  32512. precision,
  32513. inputsCode,
  32514. blockCode,
  32515. headerCode
  32516. };
  32517. } else {
  32518. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  32519. }
  32520. };
  32521. /**
  32522. * This class represents a GLSL node function.
  32523. *
  32524. * @augments NodeFunction
  32525. */
  32526. class GLSLNodeFunction extends NodeFunction {
  32527. /**
  32528. * Constructs a new GLSL node function.
  32529. *
  32530. * @param {String} source - The GLSL source.
  32531. */
  32532. constructor( source ) {
  32533. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  32534. super( type, inputs, name, precision );
  32535. this.inputsCode = inputsCode;
  32536. this.blockCode = blockCode;
  32537. this.headerCode = headerCode;
  32538. }
  32539. /**
  32540. * This method returns the GLSL code of the node function.
  32541. *
  32542. * @param {String} [name=this.name] - The function's name.
  32543. * @return {String} The shader code.
  32544. */
  32545. getCode( name = this.name ) {
  32546. let code;
  32547. const blockCode = this.blockCode;
  32548. if ( blockCode !== '' ) {
  32549. const { type, inputsCode, headerCode, precision } = this;
  32550. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  32551. if ( precision !== '' ) {
  32552. declarationCode = `${ precision } ${ declarationCode }`;
  32553. }
  32554. code = headerCode + declarationCode + blockCode;
  32555. } else {
  32556. // interface function
  32557. code = '';
  32558. }
  32559. return code;
  32560. }
  32561. }
  32562. /**
  32563. * A GLSL node parser.
  32564. *
  32565. * @augments NodeParser
  32566. */
  32567. class GLSLNodeParser extends NodeParser {
  32568. /**
  32569. * The method parses the given GLSL code an returns a node function.
  32570. *
  32571. * @param {String} source - The GLSL code.
  32572. * @return {GLSLNodeFunction} A node function.
  32573. */
  32574. parseFunction( source ) {
  32575. return new GLSLNodeFunction( source );
  32576. }
  32577. }
  32578. const _outputNodeMap = new WeakMap();
  32579. const _chainKeys$2 = [];
  32580. const _cacheKeyValues = [];
  32581. /**
  32582. * This renderer module manages node-related objects and is the
  32583. * primary interface between the renderer and the node system.
  32584. *
  32585. * @private
  32586. * @augments DataMap
  32587. */
  32588. class Nodes extends DataMap {
  32589. /**
  32590. * Constructs a new nodes management component.
  32591. *
  32592. * @param {Renderer} renderer - The renderer.
  32593. * @param {Backend} backend - The renderer's backend.
  32594. */
  32595. constructor( renderer, backend ) {
  32596. super();
  32597. /**
  32598. * The renderer.
  32599. *
  32600. * @type {Renderer}
  32601. */
  32602. this.renderer = renderer;
  32603. /**
  32604. * The renderer's backend.
  32605. *
  32606. * @type {Backend}
  32607. */
  32608. this.backend = backend;
  32609. /**
  32610. * The node frame.
  32611. *
  32612. * @type {Renderer}
  32613. */
  32614. this.nodeFrame = new NodeFrame();
  32615. /**
  32616. * A cache for managing node builder states.
  32617. *
  32618. * @type {Map<Number,NodeBuilderState>}
  32619. */
  32620. this.nodeBuilderCache = new Map();
  32621. /**
  32622. * A cache for managing data cache key data.
  32623. *
  32624. * @type {ChainMap}
  32625. */
  32626. this.callHashCache = new ChainMap();
  32627. /**
  32628. * A cache for managing node uniforms group data.
  32629. *
  32630. * @type {ChainMap}
  32631. */
  32632. this.groupsData = new ChainMap();
  32633. /**
  32634. * A cache for managing node objects of
  32635. * scene properties like fog or environments.
  32636. *
  32637. * @type {Object<String,WeakMap>}
  32638. */
  32639. this.cacheLib = {};
  32640. }
  32641. /**
  32642. * Returns `true` if the given node uniforms group must be updated or not.
  32643. *
  32644. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  32645. * @return {Boolean} Whether the node uniforms group requires an update or not.
  32646. */
  32647. updateGroup( nodeUniformsGroup ) {
  32648. const groupNode = nodeUniformsGroup.groupNode;
  32649. const name = groupNode.name;
  32650. // objectGroup is always updated
  32651. if ( name === objectGroup.name ) return true;
  32652. // renderGroup is updated once per render/compute call
  32653. if ( name === renderGroup.name ) {
  32654. const uniformsGroupData = this.get( nodeUniformsGroup );
  32655. const renderId = this.nodeFrame.renderId;
  32656. if ( uniformsGroupData.renderId !== renderId ) {
  32657. uniformsGroupData.renderId = renderId;
  32658. return true;
  32659. }
  32660. return false;
  32661. }
  32662. // frameGroup is updated once per frame
  32663. if ( name === frameGroup.name ) {
  32664. const uniformsGroupData = this.get( nodeUniformsGroup );
  32665. const frameId = this.nodeFrame.frameId;
  32666. if ( uniformsGroupData.frameId !== frameId ) {
  32667. uniformsGroupData.frameId = frameId;
  32668. return true;
  32669. }
  32670. return false;
  32671. }
  32672. // other groups are updated just when groupNode.needsUpdate is true
  32673. _chainKeys$2[ 0 ] = groupNode;
  32674. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  32675. let groupData = this.groupsData.get( _chainKeys$2 );
  32676. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  32677. _chainKeys$2.length = 0;
  32678. if ( groupData.version !== groupNode.version ) {
  32679. groupData.version = groupNode.version;
  32680. return true;
  32681. }
  32682. return false;
  32683. }
  32684. /**
  32685. * Returns the cache key for the given render object.
  32686. *
  32687. * @param {RenderObject} renderObject - The render object.
  32688. * @return {Number} The cache key.
  32689. */
  32690. getForRenderCacheKey( renderObject ) {
  32691. return renderObject.initialCacheKey;
  32692. }
  32693. /**
  32694. * Returns a node builder state for the given render object.
  32695. *
  32696. * @param {RenderObject} renderObject - The render object.
  32697. * @return {NodeBuilderState} The node builder state.
  32698. */
  32699. getForRender( renderObject ) {
  32700. const renderObjectData = this.get( renderObject );
  32701. let nodeBuilderState = renderObjectData.nodeBuilderState;
  32702. if ( nodeBuilderState === undefined ) {
  32703. const { nodeBuilderCache } = this;
  32704. const cacheKey = this.getForRenderCacheKey( renderObject );
  32705. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  32706. if ( nodeBuilderState === undefined ) {
  32707. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  32708. nodeBuilder.scene = renderObject.scene;
  32709. nodeBuilder.material = renderObject.material;
  32710. nodeBuilder.camera = renderObject.camera;
  32711. nodeBuilder.context.material = renderObject.material;
  32712. nodeBuilder.lightsNode = renderObject.lightsNode;
  32713. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  32714. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  32715. nodeBuilder.clippingContext = renderObject.clippingContext;
  32716. nodeBuilder.build();
  32717. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32718. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  32719. }
  32720. nodeBuilderState.usedTimes ++;
  32721. renderObjectData.nodeBuilderState = nodeBuilderState;
  32722. }
  32723. return nodeBuilderState;
  32724. }
  32725. /**
  32726. * Deletes the given object from the internal data map
  32727. *
  32728. * @param {Any} object - The object to delete.
  32729. * @return {Object?} The deleted dictionary.
  32730. */
  32731. delete( object ) {
  32732. if ( object.isRenderObject ) {
  32733. const nodeBuilderState = this.get( object ).nodeBuilderState;
  32734. nodeBuilderState.usedTimes --;
  32735. if ( nodeBuilderState.usedTimes === 0 ) {
  32736. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  32737. }
  32738. }
  32739. return super.delete( object );
  32740. }
  32741. /**
  32742. * Returns a node builder state for the given compute node.
  32743. *
  32744. * @param {Node} computeNode - The compute node.
  32745. * @return {NodeBuilderState} The node builder state.
  32746. */
  32747. getForCompute( computeNode ) {
  32748. const computeData = this.get( computeNode );
  32749. let nodeBuilderState = computeData.nodeBuilderState;
  32750. if ( nodeBuilderState === undefined ) {
  32751. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  32752. nodeBuilder.build();
  32753. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32754. computeData.nodeBuilderState = nodeBuilderState;
  32755. }
  32756. return nodeBuilderState;
  32757. }
  32758. /**
  32759. * Creates a node builder state for the given node builder.
  32760. *
  32761. * @private
  32762. * @param {NodeBuilder} nodeBuilder - The node builder.
  32763. * @return {NodeBuilderState} The node builder state.
  32764. */
  32765. _createNodeBuilderState( nodeBuilder ) {
  32766. return new NodeBuilderState(
  32767. nodeBuilder.vertexShader,
  32768. nodeBuilder.fragmentShader,
  32769. nodeBuilder.computeShader,
  32770. nodeBuilder.getAttributesArray(),
  32771. nodeBuilder.getBindings(),
  32772. nodeBuilder.updateNodes,
  32773. nodeBuilder.updateBeforeNodes,
  32774. nodeBuilder.updateAfterNodes,
  32775. nodeBuilder.observer,
  32776. nodeBuilder.transforms
  32777. );
  32778. }
  32779. /**
  32780. * Returns an environment node for the current configured
  32781. * scene environment.
  32782. *
  32783. * @param {Scene} scene - The scene.
  32784. * @return {Node} A node representing the current scene environment.
  32785. */
  32786. getEnvironmentNode( scene ) {
  32787. this.updateEnvironment( scene );
  32788. let environmentNode = null;
  32789. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  32790. environmentNode = scene.environmentNode;
  32791. } else {
  32792. const sceneData = this.get( scene );
  32793. if ( sceneData.environmentNode ) {
  32794. environmentNode = sceneData.environmentNode;
  32795. }
  32796. }
  32797. return environmentNode;
  32798. }
  32799. /**
  32800. * Returns a background node for the current configured
  32801. * scene background.
  32802. *
  32803. * @param {Scene} scene - The scene.
  32804. * @return {Node} A node representing the current scene background.
  32805. */
  32806. getBackgroundNode( scene ) {
  32807. this.updateBackground( scene );
  32808. let backgroundNode = null;
  32809. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  32810. backgroundNode = scene.backgroundNode;
  32811. } else {
  32812. const sceneData = this.get( scene );
  32813. if ( sceneData.backgroundNode ) {
  32814. backgroundNode = sceneData.backgroundNode;
  32815. }
  32816. }
  32817. return backgroundNode;
  32818. }
  32819. /**
  32820. * Returns a fog node for the current configured scene fog.
  32821. *
  32822. * @param {Scene} scene - The scene.
  32823. * @return {Node} A node representing the current scene fog.
  32824. */
  32825. getFogNode( scene ) {
  32826. this.updateFog( scene );
  32827. return scene.fogNode || this.get( scene ).fogNode || null;
  32828. }
  32829. /**
  32830. * Returns a cache key for the given scene and lights node.
  32831. * This key is used by `RenderObject` as a part of the dynamic
  32832. * cache key (a key that must be checked every time the render
  32833. * objects is drawn).
  32834. *
  32835. * @param {Scene} scene - The scene.
  32836. * @param {LightsNode} lightsNode - The lights node.
  32837. * @return {Number} The cache key.
  32838. */
  32839. getCacheKey( scene, lightsNode ) {
  32840. _chainKeys$2[ 0 ] = scene;
  32841. _chainKeys$2[ 1 ] = lightsNode;
  32842. const callId = this.renderer.info.calls;
  32843. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  32844. if ( cacheKeyData.callId !== callId ) {
  32845. const environmentNode = this.getEnvironmentNode( scene );
  32846. const fogNode = this.getFogNode( scene );
  32847. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  32848. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  32849. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  32850. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  32851. cacheKeyData.callId = callId;
  32852. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  32853. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  32854. _cacheKeyValues.length = 0;
  32855. }
  32856. _chainKeys$2.length = 0;
  32857. return cacheKeyData.cacheKey;
  32858. }
  32859. /**
  32860. * A boolean that indicates whether tone mapping should be enabled
  32861. * or not.
  32862. *
  32863. * @type {Boolean}
  32864. */
  32865. get isToneMappingState() {
  32866. return this.renderer.getRenderTarget() ? false : true;
  32867. }
  32868. /**
  32869. * If a scene background is configured, this method makes sure to
  32870. * represent the background with a corresponding node-based implementation.
  32871. *
  32872. * @param {Scene} scene - The scene.
  32873. */
  32874. updateBackground( scene ) {
  32875. const sceneData = this.get( scene );
  32876. const background = scene.background;
  32877. if ( background ) {
  32878. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  32879. if ( sceneData.background !== background || forceUpdate ) {
  32880. const backgroundNode = this.getCacheNode( 'background', background, () => {
  32881. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  32882. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  32883. return pmremTexture( background );
  32884. } else {
  32885. let envMap;
  32886. if ( background.isCubeTexture === true ) {
  32887. envMap = cubeTexture( background );
  32888. } else {
  32889. envMap = texture( background );
  32890. }
  32891. return cubeMapNode( envMap );
  32892. }
  32893. } else if ( background.isTexture === true ) {
  32894. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  32895. } else if ( background.isColor !== true ) {
  32896. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  32897. }
  32898. }, forceUpdate );
  32899. sceneData.backgroundNode = backgroundNode;
  32900. sceneData.background = background;
  32901. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  32902. }
  32903. } else if ( sceneData.backgroundNode ) {
  32904. delete sceneData.backgroundNode;
  32905. delete sceneData.background;
  32906. }
  32907. }
  32908. /**
  32909. * This method is part of the caching of nodes which are used to represents the
  32910. * scene's background, fog or environment.
  32911. *
  32912. * @param {String} type - The type of object to cache.
  32913. * @param {Object} object - The object.
  32914. * @param {Function} callback - A callback that produces a node representation for the given object.
  32915. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  32916. * @return {Node} The node representation.
  32917. */
  32918. getCacheNode( type, object, callback, forceUpdate = false ) {
  32919. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  32920. let node = nodeCache.get( object );
  32921. if ( node === undefined || forceUpdate ) {
  32922. node = callback();
  32923. nodeCache.set( object, node );
  32924. }
  32925. return node;
  32926. }
  32927. /**
  32928. * If a scene fog is configured, this method makes sure to
  32929. * represent the fog with a corresponding node-based implementation.
  32930. *
  32931. * @param {Scene} scene - The scene.
  32932. */
  32933. updateFog( scene ) {
  32934. const sceneData = this.get( scene );
  32935. const sceneFog = scene.fog;
  32936. if ( sceneFog ) {
  32937. if ( sceneData.fog !== sceneFog ) {
  32938. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  32939. if ( sceneFog.isFogExp2 ) {
  32940. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32941. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  32942. return fog( color, densityFogFactor( density ) );
  32943. } else if ( sceneFog.isFog ) {
  32944. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32945. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  32946. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  32947. return fog( color, rangeFogFactor( near, far ) );
  32948. } else {
  32949. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  32950. }
  32951. } );
  32952. sceneData.fogNode = fogNode;
  32953. sceneData.fog = sceneFog;
  32954. }
  32955. } else {
  32956. delete sceneData.fogNode;
  32957. delete sceneData.fog;
  32958. }
  32959. }
  32960. /**
  32961. * If a scene environment is configured, this method makes sure to
  32962. * represent the environment with a corresponding node-based implementation.
  32963. *
  32964. * @param {Scene} scene - The scene.
  32965. */
  32966. updateEnvironment( scene ) {
  32967. const sceneData = this.get( scene );
  32968. const environment = scene.environment;
  32969. if ( environment ) {
  32970. if ( sceneData.environment !== environment ) {
  32971. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  32972. if ( environment.isCubeTexture === true ) {
  32973. return cubeTexture( environment );
  32974. } else if ( environment.isTexture === true ) {
  32975. return texture( environment );
  32976. } else {
  32977. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32978. }
  32979. } );
  32980. sceneData.environmentNode = environmentNode;
  32981. sceneData.environment = environment;
  32982. }
  32983. } else if ( sceneData.environmentNode ) {
  32984. delete sceneData.environmentNode;
  32985. delete sceneData.environment;
  32986. }
  32987. }
  32988. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32989. const nodeFrame = this.nodeFrame;
  32990. nodeFrame.renderer = renderer;
  32991. nodeFrame.scene = scene;
  32992. nodeFrame.object = object;
  32993. nodeFrame.camera = camera;
  32994. nodeFrame.material = material;
  32995. return nodeFrame;
  32996. }
  32997. getNodeFrameForRender( renderObject ) {
  32998. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32999. }
  33000. /**
  33001. * Returns the current output cache key.
  33002. *
  33003. * @return {String} The output cache key.
  33004. */
  33005. getOutputCacheKey() {
  33006. const renderer = this.renderer;
  33007. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  33008. }
  33009. /**
  33010. * Checks if the output configuration (tone mapping and color space) for
  33011. * the given target has changed.
  33012. *
  33013. * @param {Texture} outputTarget - The output target.
  33014. * @return {Boolean} Whether the output configuration has changed or not.
  33015. */
  33016. hasOutputChange( outputTarget ) {
  33017. const cacheKey = _outputNodeMap.get( outputTarget );
  33018. return cacheKey !== this.getOutputCacheKey();
  33019. }
  33020. /**
  33021. * Returns a node that represents the output configuration (tone mapping and
  33022. * color space) for the current target.
  33023. *
  33024. * @param {Texture} outputTarget - The output target.
  33025. * @return {Node} The output node.
  33026. */
  33027. getOutputNode( outputTarget ) {
  33028. const renderer = this.renderer;
  33029. const cacheKey = this.getOutputCacheKey();
  33030. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  33031. _outputNodeMap.set( outputTarget, cacheKey );
  33032. return output;
  33033. }
  33034. /**
  33035. * Triggers the call of `updateBefore()` methods
  33036. * for all nodes of the given render object.
  33037. *
  33038. * @param {RenderObject} renderObject - The render object.
  33039. */
  33040. updateBefore( renderObject ) {
  33041. const nodeBuilder = renderObject.getNodeBuilderState();
  33042. for ( const node of nodeBuilder.updateBeforeNodes ) {
  33043. // update frame state for each node
  33044. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  33045. }
  33046. }
  33047. /**
  33048. * Triggers the call of `updateAfter()` methods
  33049. * for all nodes of the given render object.
  33050. *
  33051. * @param {RenderObject} renderObject - The render object.
  33052. */
  33053. updateAfter( renderObject ) {
  33054. const nodeBuilder = renderObject.getNodeBuilderState();
  33055. for ( const node of nodeBuilder.updateAfterNodes ) {
  33056. // update frame state for each node
  33057. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  33058. }
  33059. }
  33060. /**
  33061. * Triggers the call of `update()` methods
  33062. * for all nodes of the given compute node.
  33063. *
  33064. * @param {Node} computeNode - The compute node.
  33065. */
  33066. updateForCompute( computeNode ) {
  33067. const nodeFrame = this.getNodeFrame();
  33068. const nodeBuilder = this.getForCompute( computeNode );
  33069. for ( const node of nodeBuilder.updateNodes ) {
  33070. nodeFrame.updateNode( node );
  33071. }
  33072. }
  33073. /**
  33074. * Triggers the call of `update()` methods
  33075. * for all nodes of the given compute node.
  33076. *
  33077. * @param {RenderObject} renderObject - The render object.
  33078. */
  33079. updateForRender( renderObject ) {
  33080. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33081. const nodeBuilder = renderObject.getNodeBuilderState();
  33082. for ( const node of nodeBuilder.updateNodes ) {
  33083. nodeFrame.updateNode( node );
  33084. }
  33085. }
  33086. /**
  33087. * Returns `true` if the given render object requires a refresh.
  33088. *
  33089. * @param {RenderObject} renderObject - The render object.
  33090. * @return {Boolean} Whether the given render object requires a refresh or not.
  33091. */
  33092. needsRefresh( renderObject ) {
  33093. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33094. const monitor = renderObject.getMonitor();
  33095. return monitor.needsRefresh( renderObject, nodeFrame );
  33096. }
  33097. /**
  33098. * Frees the internal resources.
  33099. */
  33100. dispose() {
  33101. super.dispose();
  33102. this.nodeFrame = new NodeFrame();
  33103. this.nodeBuilderCache = new Map();
  33104. this.cacheLib = {};
  33105. }
  33106. }
  33107. const _plane = /*@__PURE__*/ new Plane();
  33108. /**
  33109. * Represents the state that is used to perform clipping via clipping planes.
  33110. * There is a default clipping context for each render context. When the
  33111. * scene holds instances of `ClippingGroup`, there will be a context for each
  33112. * group.
  33113. *
  33114. * @private
  33115. */
  33116. class ClippingContext {
  33117. /**
  33118. * Constructs a new clipping context.
  33119. *
  33120. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  33121. */
  33122. constructor( parentContext = null ) {
  33123. /**
  33124. * The clipping context's version.
  33125. *
  33126. * @type {Number}
  33127. * @readonly
  33128. */
  33129. this.version = 0;
  33130. /**
  33131. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  33132. *
  33133. * @type {Boolean?}
  33134. * @default null
  33135. */
  33136. this.clipIntersection = null;
  33137. /**
  33138. * The clipping context's cache key.
  33139. *
  33140. * @type {String}
  33141. */
  33142. this.cacheKey = '';
  33143. /**
  33144. * Whether the shadow pass is active or not.
  33145. *
  33146. * @type {Boolean}
  33147. * @default false
  33148. */
  33149. this.shadowPass = false;
  33150. /**
  33151. * The view normal matrix.
  33152. *
  33153. * @type {Matrix3}
  33154. */
  33155. this.viewNormalMatrix = new Matrix3();
  33156. /**
  33157. * Internal cache for maintaining clipping contexts.
  33158. *
  33159. * @type {WeakMap<ClippingGroup,ClippingContext>}
  33160. */
  33161. this.clippingGroupContexts = new WeakMap();
  33162. /**
  33163. * The intersection planes.
  33164. *
  33165. * @type {Array<Vector4>}
  33166. */
  33167. this.intersectionPlanes = [];
  33168. /**
  33169. * The intersection planes.
  33170. *
  33171. * @type {Array<Vector4>}
  33172. */
  33173. this.unionPlanes = [];
  33174. /**
  33175. * The version of the clipping context's parent context.
  33176. *
  33177. * @type {Number?}
  33178. * @readonly
  33179. */
  33180. this.parentVersion = null;
  33181. if ( parentContext !== null ) {
  33182. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  33183. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  33184. this.shadowPass = parentContext.shadowPass;
  33185. this.viewMatrix = parentContext.viewMatrix;
  33186. }
  33187. }
  33188. /**
  33189. * Projects the given source clipping planes and writes the result into the
  33190. * destination array.
  33191. *
  33192. * @param {Array<Plane>} source - The source clipping planes.
  33193. * @param {Array<Vector4>} destination - The destination.
  33194. * @param {Number} offset - The offset.
  33195. */
  33196. projectPlanes( source, destination, offset ) {
  33197. const l = source.length;
  33198. for ( let i = 0; i < l; i ++ ) {
  33199. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  33200. const v = destination[ offset + i ];
  33201. const normal = _plane.normal;
  33202. v.x = - normal.x;
  33203. v.y = - normal.y;
  33204. v.z = - normal.z;
  33205. v.w = _plane.constant;
  33206. }
  33207. }
  33208. /**
  33209. * Updates the root clipping context of a scene.
  33210. *
  33211. * @param {Scene} scene - The scene.
  33212. * @param {Camera} camera - The camera that is used to render the scene.
  33213. */
  33214. updateGlobal( scene, camera ) {
  33215. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  33216. this.viewMatrix = camera.matrixWorldInverse;
  33217. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  33218. }
  33219. /**
  33220. * Updates the clipping context.
  33221. *
  33222. * @param {ClippingContext} parentContext - The parent context.
  33223. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  33224. */
  33225. update( parentContext, clippingGroup ) {
  33226. let update = false;
  33227. if ( parentContext.version !== this.parentVersion ) {
  33228. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  33229. this.unionPlanes = Array.from( parentContext.unionPlanes );
  33230. this.parentVersion = parentContext.version;
  33231. }
  33232. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  33233. this.clipIntersection = clippingGroup.clipIntersection;
  33234. if ( this.clipIntersection ) {
  33235. this.unionPlanes.length = parentContext.unionPlanes.length;
  33236. } else {
  33237. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  33238. }
  33239. }
  33240. const srcClippingPlanes = clippingGroup.clippingPlanes;
  33241. const l = srcClippingPlanes.length;
  33242. let dstClippingPlanes;
  33243. let offset;
  33244. if ( this.clipIntersection ) {
  33245. dstClippingPlanes = this.intersectionPlanes;
  33246. offset = parentContext.intersectionPlanes.length;
  33247. } else {
  33248. dstClippingPlanes = this.unionPlanes;
  33249. offset = parentContext.unionPlanes.length;
  33250. }
  33251. if ( dstClippingPlanes.length !== offset + l ) {
  33252. dstClippingPlanes.length = offset + l;
  33253. for ( let i = 0; i < l; i ++ ) {
  33254. dstClippingPlanes[ offset + i ] = new Vector4();
  33255. }
  33256. update = true;
  33257. }
  33258. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  33259. if ( update ) {
  33260. this.version ++;
  33261. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  33262. }
  33263. }
  33264. /**
  33265. * Returns a clipping context for the given clipping group.
  33266. *
  33267. * @param {ClippingGroup} clippingGroup - The clipping group.
  33268. * @return {ClippingContext} The clipping context.
  33269. */
  33270. getGroupContext( clippingGroup ) {
  33271. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  33272. let context = this.clippingGroupContexts.get( clippingGroup );
  33273. if ( context === undefined ) {
  33274. context = new ClippingContext( this );
  33275. this.clippingGroupContexts.set( clippingGroup, context );
  33276. }
  33277. context.update( this, clippingGroup );
  33278. return context;
  33279. }
  33280. /**
  33281. * The count of union clipping planes.
  33282. *
  33283. * @type {Number}
  33284. * @readonly
  33285. */
  33286. get unionClippingCount() {
  33287. return this.unionPlanes.length;
  33288. }
  33289. }
  33290. /**
  33291. * This module is used to represent render bundles inside the renderer
  33292. * for further processing.
  33293. *
  33294. * @private
  33295. */
  33296. class RenderBundle {
  33297. /**
  33298. * Constructs a new bundle group.
  33299. *
  33300. * @param {BundleGroup} bundleGroup - The bundle group.
  33301. * @param {Camera} camera - The camera the bundle group is rendered with.
  33302. */
  33303. constructor( bundleGroup, camera ) {
  33304. this.bundleGroup = bundleGroup;
  33305. this.camera = camera;
  33306. }
  33307. }
  33308. const _chainKeys$1 = [];
  33309. /**
  33310. * This renderer module manages render bundles.
  33311. *
  33312. * @private
  33313. */
  33314. class RenderBundles {
  33315. /**
  33316. * Constructs a new render bundle management component.
  33317. */
  33318. constructor() {
  33319. /**
  33320. * A chain map for maintaining the render bundles.
  33321. *
  33322. * @type {ChainMap}
  33323. */
  33324. this.bundles = new ChainMap();
  33325. }
  33326. /**
  33327. * Returns a render bundle for the given bundle group and camera.
  33328. *
  33329. * @param {BundleGroup} bundleGroup - The bundle group.
  33330. * @param {Camera} camera - The camera the bundle group is rendered with.
  33331. * @return {RenderBundle} The render bundle.
  33332. */
  33333. get( bundleGroup, camera ) {
  33334. const bundles = this.bundles;
  33335. _chainKeys$1[ 0 ] = bundleGroup;
  33336. _chainKeys$1[ 1 ] = camera;
  33337. let bundle = bundles.get( _chainKeys$1 );
  33338. if ( bundle === undefined ) {
  33339. bundle = new RenderBundle( bundleGroup, camera );
  33340. bundles.set( _chainKeys$1, bundle );
  33341. }
  33342. _chainKeys$1.length = 0;
  33343. return bundle;
  33344. }
  33345. /**
  33346. * Frees all internal resources.
  33347. */
  33348. dispose() {
  33349. this.bundles = new ChainMap();
  33350. }
  33351. }
  33352. /**
  33353. * The purpose of a node library is to assign node implementations
  33354. * to existing library features. In `WebGPURenderer` lights, materials
  33355. * which are not based on `NodeMaterial` as well as tone mapping techniques
  33356. * are implemented with node-based modules.
  33357. *
  33358. * @private
  33359. */
  33360. class NodeLibrary {
  33361. /**
  33362. * Constructs a new node library.
  33363. */
  33364. constructor() {
  33365. /**
  33366. * A weak map that maps lights to light nodes.
  33367. *
  33368. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  33369. */
  33370. this.lightNodes = new WeakMap();
  33371. /**
  33372. * A map that maps materials to node materials.
  33373. *
  33374. * @type {Map<String,NodeMaterial.constructor>}
  33375. */
  33376. this.materialNodes = new Map();
  33377. /**
  33378. * A map that maps tone mapping techniques (constants)
  33379. * to tone mapping node functions.
  33380. *
  33381. * @type {Map<Number,Function>}
  33382. */
  33383. this.toneMappingNodes = new Map();
  33384. }
  33385. /**
  33386. * Returns a matching node material instance for the given material object.
  33387. *
  33388. * This method also assigns/copies the properties of the given material object
  33389. * to the node material. This is done to make sure the current material
  33390. * configuration carries over to the node version.
  33391. *
  33392. * @param {Material} material - A material.
  33393. * @return {NodeMaterial} The corresponding node material.
  33394. */
  33395. fromMaterial( material ) {
  33396. if ( material.isNodeMaterial ) return material;
  33397. let nodeMaterial = null;
  33398. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  33399. if ( nodeMaterialClass !== null ) {
  33400. nodeMaterial = new nodeMaterialClass();
  33401. for ( const key in material ) {
  33402. nodeMaterial[ key ] = material[ key ];
  33403. }
  33404. }
  33405. return nodeMaterial;
  33406. }
  33407. /**
  33408. * Adds a tone mapping node function for a tone mapping technique (constant).
  33409. *
  33410. * @param {Function} toneMappingNode - The tone mapping node function.
  33411. * @param {Number} toneMapping - The tone mapping.
  33412. */
  33413. addToneMapping( toneMappingNode, toneMapping ) {
  33414. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  33415. }
  33416. /**
  33417. * Returns a tone mapping node function for a tone mapping technique (constant).
  33418. *
  33419. * @param {Number} toneMapping - The tone mapping.
  33420. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  33421. */
  33422. getToneMappingFunction( toneMapping ) {
  33423. return this.toneMappingNodes.get( toneMapping ) || null;
  33424. }
  33425. /**
  33426. * Returns a node material class definition for a material type.
  33427. *
  33428. * @param {String} materialType - The material type.
  33429. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  33430. */
  33431. getMaterialNodeClass( materialType ) {
  33432. return this.materialNodes.get( materialType ) || null;
  33433. }
  33434. /**
  33435. * Adds a node material class definition for a given material type.
  33436. *
  33437. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  33438. * @param {String} materialClassType - The material type.
  33439. */
  33440. addMaterial( materialNodeClass, materialClassType ) {
  33441. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  33442. }
  33443. /**
  33444. * Returns a light node class definition for a light class definition.
  33445. *
  33446. * @param {Light.constructor} light - The light class definition.
  33447. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  33448. */
  33449. getLightNodeClass( light ) {
  33450. return this.lightNodes.get( light ) || null;
  33451. }
  33452. /**
  33453. * Adds a light node class definition for a given light class definition.
  33454. *
  33455. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  33456. * @param {Light.constructor} lightClass - The light class definition.
  33457. */
  33458. addLight( lightNodeClass, lightClass ) {
  33459. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  33460. }
  33461. /**
  33462. * Adds a node class definition for the given type to the provided type library.
  33463. *
  33464. * @param {Any} nodeClass - The node class definition.
  33465. * @param {Number|String} type - The object type.
  33466. * @param {Map} library - The type library.
  33467. */
  33468. addType( nodeClass, type, library ) {
  33469. if ( library.has( type ) ) {
  33470. console.warn( `Redefinition of node ${ type }` );
  33471. return;
  33472. }
  33473. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33474. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  33475. library.set( type, nodeClass );
  33476. }
  33477. /**
  33478. * Adds a node class definition for the given class definition to the provided type library.
  33479. *
  33480. * @param {Any} nodeClass - The node class definition.
  33481. * @param {Any} baseClass - The class definition.
  33482. * @param {WeakMap} library - The type library.
  33483. */
  33484. addClass( nodeClass, baseClass, library ) {
  33485. if ( library.has( baseClass ) ) {
  33486. console.warn( `Redefinition of node ${ baseClass.name }` );
  33487. return;
  33488. }
  33489. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  33490. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  33491. library.set( baseClass, nodeClass );
  33492. }
  33493. }
  33494. const _defaultLights = /*@__PURE__*/ new LightsNode();
  33495. const _chainKeys = [];
  33496. /**
  33497. * This renderer module manages the lights nodes which are unique
  33498. * per scene and camera combination.
  33499. *
  33500. * The lights node itself is later configured in the render list
  33501. * with the actual lights from the scene.
  33502. *
  33503. * @private
  33504. * @augments ChainMap
  33505. */
  33506. class Lighting extends ChainMap {
  33507. /**
  33508. * Constructs a lighting management component.
  33509. */
  33510. constructor() {
  33511. super();
  33512. }
  33513. /**
  33514. * Creates a new lights node for the given array of lights.
  33515. *
  33516. * @param {Array<Light>} lights - The render object.
  33517. * @return {LightsNode} The lights node.
  33518. */
  33519. createNode( lights = [] ) {
  33520. return new LightsNode().setLights( lights );
  33521. }
  33522. /**
  33523. * Returns a lights node for the given scene and camera.
  33524. *
  33525. * @param {Scene} scene - The scene.
  33526. * @param {Camera} camera - The camera.
  33527. * @return {LightsNode} The lights node.
  33528. */
  33529. getNode( scene, camera ) {
  33530. // ignore post-processing
  33531. if ( scene.isQuadMesh ) return _defaultLights;
  33532. _chainKeys[ 0 ] = scene;
  33533. _chainKeys[ 1 ] = camera;
  33534. let node = this.get( _chainKeys );
  33535. if ( node === undefined ) {
  33536. node = this.createNode();
  33537. this.set( _chainKeys, node );
  33538. }
  33539. _chainKeys.length = 0;
  33540. return node;
  33541. }
  33542. }
  33543. /**
  33544. * A special type of render target that is used when rendering
  33545. * with the WebXR Device API.
  33546. *
  33547. * @private
  33548. * @augments RenderTarget
  33549. */
  33550. class XRRenderTarget extends RenderTarget {
  33551. /**
  33552. * Constructs a new XR render target.
  33553. *
  33554. * @param {Number} [width=1] - The width of the render target.
  33555. * @param {Number} [height=1] - The height of the render target.
  33556. * @param {Object} [options={}] - The configuration options.
  33557. */
  33558. constructor( width = 1, height = 1, options = {} ) {
  33559. super( width, height, options );
  33560. /**
  33561. * This flag can be used for type testing.
  33562. *
  33563. * @type {Boolean}
  33564. * @readonly
  33565. * @default true
  33566. */
  33567. this.isXRRenderTarget = true;
  33568. /**
  33569. * Whether the attachments of the render target
  33570. * are defined by external textures. This flag is
  33571. * set to `true` when using the WebXR Layers API.
  33572. *
  33573. * @type {Boolean}
  33574. * @default false
  33575. */
  33576. this.hasExternalTextures = false;
  33577. /**
  33578. * Whether a depth buffer should automatically be allocated
  33579. * for this XR render target or not.
  33580. *
  33581. * Allocating a depth buffer is the default behavior of XR render
  33582. * targets. However, when using the WebXR Layers API, this flag
  33583. * must be set to `false` when the `ignoreDepthValues` property of
  33584. * the projection layers evaluates to `false`.
  33585. *
  33586. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  33587. *
  33588. * @type {Boolean}
  33589. * @default true
  33590. */
  33591. this.autoAllocateDepthBuffer = true;
  33592. }
  33593. copy( source ) {
  33594. super.copy( source );
  33595. this.hasExternalTextures = source.hasExternalTextures;
  33596. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  33597. return this;
  33598. }
  33599. }
  33600. const _cameraLPos = /*@__PURE__*/ new Vector3();
  33601. const _cameraRPos = /*@__PURE__*/ new Vector3();
  33602. /**
  33603. * The XR manager is built on top of the WebXR Device API to
  33604. * manage XR sessions with `WebGPURenderer`.
  33605. *
  33606. * XR is currently only supported with a WebGL 2 backend.
  33607. *
  33608. * @augments EventDispatcher
  33609. */
  33610. class XRManager extends EventDispatcher {
  33611. /**
  33612. * Constructs a new XR manager.
  33613. *
  33614. * @param {Renderer} renderer - The renderer.
  33615. */
  33616. constructor( renderer ) {
  33617. super();
  33618. /**
  33619. * This flag globally enables XR rendering.
  33620. *
  33621. * @type {Boolean}
  33622. * @default false
  33623. */
  33624. this.enabled = false;
  33625. /**
  33626. * Whether the XR device is currently presenting or not.
  33627. *
  33628. * @type {Boolean}
  33629. * @default false
  33630. * @readonly
  33631. */
  33632. this.isPresenting = false;
  33633. /**
  33634. * Whether the XR camera should automatically be updated or not.
  33635. *
  33636. * @type {Boolean}
  33637. * @default true
  33638. */
  33639. this.cameraAutoUpdate = true;
  33640. /**
  33641. * The renderer.
  33642. *
  33643. * @private
  33644. * @type {Renderer}
  33645. */
  33646. this._renderer = renderer;
  33647. // camera
  33648. /**
  33649. * Represents the camera for the left eye.
  33650. *
  33651. * @private
  33652. * @type {PerspectiveCamera}
  33653. */
  33654. this._cameraL = new PerspectiveCamera();
  33655. this._cameraL.viewport = new Vector4();
  33656. /**
  33657. * Represents the camera for the right eye.
  33658. *
  33659. * @private
  33660. * @type {PerspectiveCamera}
  33661. */
  33662. this._cameraR = new PerspectiveCamera();
  33663. this._cameraR.viewport = new Vector4();
  33664. /**
  33665. * A list of cameras used for rendering the XR views.
  33666. *
  33667. * @private
  33668. * @type {Array<Camera>}
  33669. */
  33670. this._cameras = [ this._cameraL, this._cameraR ];
  33671. /**
  33672. * The main XR camera.
  33673. *
  33674. * @private
  33675. * @type {ArrayCamera}
  33676. */
  33677. this._cameraXR = new ArrayCamera();
  33678. /**
  33679. * The current near value of the XR camera.
  33680. *
  33681. * @private
  33682. * @type {Number?}
  33683. * @default null
  33684. */
  33685. this._currentDepthNear = null;
  33686. /**
  33687. * The current far value of the XR camera.
  33688. *
  33689. * @private
  33690. * @type {Number?}
  33691. * @default null
  33692. */
  33693. this._currentDepthFar = null;
  33694. /**
  33695. * A list of WebXR controllers requested by the application.
  33696. *
  33697. * @private
  33698. * @type {Array<WebXRController>}
  33699. */
  33700. this._controllers = [];
  33701. /**
  33702. * A list of XR input source. Each input source belongs to
  33703. * an instance of WebXRController.
  33704. *
  33705. * @private
  33706. * @type {Array<XRInputSource?>}
  33707. */
  33708. this._controllerInputSources = [];
  33709. /**
  33710. * The current render target of the renderer.
  33711. *
  33712. * @private
  33713. * @type {RenderTarget?}
  33714. * @default null
  33715. */
  33716. this._currentRenderTarget = null;
  33717. /**
  33718. * The XR render target that represents the rendering destination
  33719. * during an active XR session.
  33720. *
  33721. * @private
  33722. * @type {RenderTarget?}
  33723. * @default null
  33724. */
  33725. this._xrRenderTarget = null;
  33726. /**
  33727. * The current animation context.
  33728. *
  33729. * @private
  33730. * @type {Window?}
  33731. * @default null
  33732. */
  33733. this._currentAnimationContext = null;
  33734. /**
  33735. * The current animation loop.
  33736. *
  33737. * @private
  33738. * @type {Function?}
  33739. * @default null
  33740. */
  33741. this._currentAnimationLoop = null;
  33742. /**
  33743. * The current pixel ratio.
  33744. *
  33745. * @private
  33746. * @type {Number?}
  33747. * @default null
  33748. */
  33749. this._currentPixelRatio = null;
  33750. /**
  33751. * The current size of the renderer's canvas
  33752. * in logical pixel unit.
  33753. *
  33754. * @private
  33755. * @type {Vector2}
  33756. */
  33757. this._currentSize = new Vector2();
  33758. /**
  33759. * The default event listener for handling events inside a XR session.
  33760. *
  33761. * @private
  33762. * @type {Function}
  33763. */
  33764. this._onSessionEvent = onSessionEvent.bind( this );
  33765. /**
  33766. * The event listener for handling the end of a XR session.
  33767. *
  33768. * @private
  33769. * @type {Function}
  33770. */
  33771. this._onSessionEnd = onSessionEnd.bind( this );
  33772. /**
  33773. * The event listener for handling the `inputsourceschange` event.
  33774. *
  33775. * @private
  33776. * @type {Function}
  33777. */
  33778. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  33779. /**
  33780. * The animation loop which is used as a replacement for the default
  33781. * animation loop of the applicatio. It is only used when a XR session
  33782. * is active.
  33783. *
  33784. * @private
  33785. * @type {Function}
  33786. */
  33787. this._onAnimationFrame = onAnimationFrame.bind( this );
  33788. /**
  33789. * The current XR reference space.
  33790. *
  33791. * @private
  33792. * @type {XRReferenceSpace?}
  33793. * @default null
  33794. */
  33795. this._referenceSpace = null;
  33796. /**
  33797. * The current XR reference space type.
  33798. *
  33799. * @private
  33800. * @type {String}
  33801. * @default 'local-floor'
  33802. */
  33803. this._referenceSpaceType = 'local-floor';
  33804. /**
  33805. * A custom reference space defined by the application.
  33806. *
  33807. * @private
  33808. * @type {XRReferenceSpace?}
  33809. * @default null
  33810. */
  33811. this._customReferenceSpace = null;
  33812. /**
  33813. * The framebuffer scale factor.
  33814. *
  33815. * @private
  33816. * @type {Number}
  33817. * @default 1
  33818. */
  33819. this._framebufferScaleFactor = 1;
  33820. /**
  33821. * The foveation factor.
  33822. *
  33823. * @private
  33824. * @type {Number}
  33825. * @default 1
  33826. */
  33827. this._foveation = 1.0;
  33828. /**
  33829. * A reference to the current XR session.
  33830. *
  33831. * @private
  33832. * @type {XRSession?}
  33833. * @default null
  33834. */
  33835. this._session = null;
  33836. /**
  33837. * A reference to the current XR base layer.
  33838. *
  33839. * @private
  33840. * @type {XRWebGLLayer?}
  33841. * @default null
  33842. */
  33843. this._glBaseLayer = null;
  33844. /**
  33845. * A reference to the current XR binding.
  33846. *
  33847. * @private
  33848. * @type {XRWebGLBinding?}
  33849. * @default null
  33850. */
  33851. this._glBinding = null;
  33852. /**
  33853. * A reference to the current XR projection layer.
  33854. *
  33855. * @private
  33856. * @type {XRProjectionLayer?}
  33857. * @default null
  33858. */
  33859. this._glProjLayer = null;
  33860. /**
  33861. * A reference to the current XR frame.
  33862. *
  33863. * @private
  33864. * @type {XRFrame?}
  33865. * @default null
  33866. */
  33867. this._xrFrame = null;
  33868. /**
  33869. * Whether to use the WebXR Layers API or not.
  33870. *
  33871. * @private
  33872. * @type {Boolean}
  33873. * @readonly
  33874. */
  33875. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  33876. }
  33877. /**
  33878. * Returns an instance of `THREE.Group` that represents the transformation
  33879. * of a XR controller in target ray space. The requested controller is defined
  33880. * by the given index.
  33881. *
  33882. * @param {Number} index - The index of the XR controller.
  33883. * @return {Group} A group that represents the controller's transformation.
  33884. */
  33885. getController( index ) {
  33886. const controller = this._getController( index );
  33887. return controller.getTargetRaySpace();
  33888. }
  33889. /**
  33890. * Returns an instance of `THREE.Group` that represents the transformation
  33891. * of a XR controller in grip space. The requested controller is defined
  33892. * by the given index.
  33893. *
  33894. * @param {Number} index - The index of the XR controller.
  33895. * @return {Group} A group that represents the controller's transformation.
  33896. */
  33897. getControllerGrip( index ) {
  33898. const controller = this._getController( index );
  33899. return controller.getGripSpace();
  33900. }
  33901. /**
  33902. * Returns an instance of `THREE.Group` that represents the transformation
  33903. * of a XR controller in hand space. The requested controller is defined
  33904. * by the given index.
  33905. *
  33906. * @param {Number} index - The index of the XR controller.
  33907. * @return {Group} A group that represents the controller's transformation.
  33908. */
  33909. getHand( index ) {
  33910. const controller = this._getController( index );
  33911. return controller.getHandSpace();
  33912. }
  33913. /**
  33914. * Returns the foveation value.
  33915. *
  33916. * @return {Number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  33917. */
  33918. getFoveation() {
  33919. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  33920. return undefined;
  33921. }
  33922. return this._foveation;
  33923. }
  33924. /**
  33925. * Sets the foveation value.
  33926. *
  33927. * @param {Number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  33928. * and `1` means maximum foveation (the edges render at lower resolution).
  33929. */
  33930. setFoveation( foveation ) {
  33931. this._foveation = foveation;
  33932. if ( this._glProjLayer !== null ) {
  33933. this._glProjLayer.fixedFoveation = foveation;
  33934. }
  33935. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  33936. this._glBaseLayer.fixedFoveation = foveation;
  33937. }
  33938. }
  33939. /**
  33940. * Returns the framebuffer scale factor.
  33941. *
  33942. * @return {Number} The framebuffer scale factor.
  33943. */
  33944. getFramebufferScaleFactor() {
  33945. return this._framebufferScaleFactor;
  33946. }
  33947. /**
  33948. * Sets the framebuffer scale factor.
  33949. *
  33950. * This method can not be used during a XR session.
  33951. *
  33952. * @param {Number} factor - The framebuffer scale factor.
  33953. */
  33954. setFramebufferScaleFactor( factor ) {
  33955. this._framebufferScaleFactor = factor;
  33956. if ( this.isPresenting === true ) {
  33957. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  33958. }
  33959. }
  33960. /**
  33961. * Returns the reference space type.
  33962. *
  33963. * @return {String} The reference space type.
  33964. */
  33965. getReferenceSpaceType() {
  33966. return this._referenceSpaceType;
  33967. }
  33968. /**
  33969. * Sets the reference space type.
  33970. *
  33971. * This method can not be used during a XR session.
  33972. *
  33973. * @param {String} type - The reference space type.
  33974. */
  33975. setReferenceSpaceType( type ) {
  33976. this._referenceSpaceType = type;
  33977. if ( this.isPresenting === true ) {
  33978. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  33979. }
  33980. }
  33981. /**
  33982. * Returns the XR reference space.
  33983. *
  33984. * @return {XRReferenceSpace} The XR reference space.
  33985. */
  33986. getReferenceSpace() {
  33987. return this._customReferenceSpace || this._referenceSpace;
  33988. }
  33989. /**
  33990. * Sets a custom XR reference space.
  33991. *
  33992. * @param {XRReferenceSpace} space - The XR reference space.
  33993. */
  33994. setReferenceSpace( space ) {
  33995. this._customReferenceSpace = space;
  33996. }
  33997. /**
  33998. * Returns the XR camera.
  33999. *
  34000. * @return {ArrayCamera} The XR camera.
  34001. */
  34002. getCamera() {
  34003. return this._cameraXR;
  34004. }
  34005. /**
  34006. * Returns the environment blend mode from the current XR session.
  34007. *
  34008. * @return {('opaque'|'additive'|'alpha-blend')?} The environment blend mode. Returns `null` when used outside of a XR session.
  34009. */
  34010. getEnvironmentBlendMode() {
  34011. if ( this._session !== null ) {
  34012. return this._session.environmentBlendMode;
  34013. }
  34014. }
  34015. /**
  34016. * Returns the current XR frame.
  34017. *
  34018. * @return {XRFrame?} The XR frame. Returns `null` when used outside a XR session.
  34019. */
  34020. getFrame() {
  34021. return this._xrFrame;
  34022. }
  34023. /**
  34024. * Returns the current XR session.
  34025. *
  34026. * @return {XRSession?} The XR session. Returns `null` when used outside a XR session.
  34027. */
  34028. getSession() {
  34029. return this._session;
  34030. }
  34031. /**
  34032. * After a XR session has been requested usually with one of the `*Button` modules, it
  34033. * is injected into the renderer with this method. This method triggers the start of
  34034. * the actual XR rendering.
  34035. *
  34036. * @async
  34037. * @param {XRSession} session - The XR session to set.
  34038. * @return {Promise} A Promise that resolves when the session has been set.
  34039. */
  34040. async setSession( session ) {
  34041. const renderer = this._renderer;
  34042. const backend = renderer.backend;
  34043. const gl = renderer.getContext();
  34044. this._session = session;
  34045. if ( session !== null ) {
  34046. 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.' );
  34047. this._currentRenderTarget = renderer.getRenderTarget();
  34048. session.addEventListener( 'select', this._onSessionEvent );
  34049. session.addEventListener( 'selectstart', this._onSessionEvent );
  34050. session.addEventListener( 'selectend', this._onSessionEvent );
  34051. session.addEventListener( 'squeeze', this._onSessionEvent );
  34052. session.addEventListener( 'squeezestart', this._onSessionEvent );
  34053. session.addEventListener( 'squeezeend', this._onSessionEvent );
  34054. session.addEventListener( 'end', this._onSessionEnd );
  34055. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34056. await backend.makeXRCompatible();
  34057. this._currentPixelRatio = renderer.getPixelRatio();
  34058. renderer.getSize( this._currentSize );
  34059. this._currentAnimationContext = renderer._animation.getContext();
  34060. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  34061. renderer._animation.stop();
  34062. //
  34063. if ( this._useLayers === true ) {
  34064. // default path using XRWebGLBinding/XRProjectionLayer
  34065. let depthFormat = null;
  34066. let depthType = null;
  34067. let glDepthFormat = null;
  34068. if ( renderer.depth ) {
  34069. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  34070. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  34071. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  34072. }
  34073. const projectionlayerInit = {
  34074. colorFormat: gl.RGBA8,
  34075. depthFormat: glDepthFormat,
  34076. scaleFactor: this._framebufferScaleFactor
  34077. };
  34078. const glBinding = new XRWebGLBinding( session, gl );
  34079. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  34080. this._glBinding = glBinding;
  34081. this._glProjLayer = glProjLayer;
  34082. session.updateRenderState( { layers: [ glProjLayer ] } );
  34083. renderer.setPixelRatio( 1 );
  34084. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  34085. this._xrRenderTarget = new XRRenderTarget(
  34086. glProjLayer.textureWidth,
  34087. glProjLayer.textureHeight,
  34088. {
  34089. format: RGBAFormat,
  34090. type: UnsignedByteType,
  34091. colorSpace: renderer.outputColorSpace,
  34092. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  34093. stencilBuffer: renderer.stencil,
  34094. samples: renderer.samples
  34095. } );
  34096. this._xrRenderTarget.hasExternalTextures = true;
  34097. } else {
  34098. // fallback to XRWebGLLayer
  34099. const layerInit = {
  34100. antialias: renderer.samples > 0,
  34101. alpha: true,
  34102. depth: renderer.depth,
  34103. stencil: renderer.stencil,
  34104. framebufferScaleFactor: this.getFramebufferScaleFactor()
  34105. };
  34106. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  34107. this._glBaseLayer = glBaseLayer;
  34108. session.updateRenderState( { baseLayer: glBaseLayer } );
  34109. renderer.setPixelRatio( 1 );
  34110. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  34111. this._xrRenderTarget = new XRRenderTarget(
  34112. glBaseLayer.framebufferWidth,
  34113. glBaseLayer.framebufferHeight,
  34114. {
  34115. format: RGBAFormat,
  34116. type: UnsignedByteType,
  34117. colorSpace: renderer.outputColorSpace,
  34118. stencilBuffer: renderer.stencil
  34119. }
  34120. );
  34121. }
  34122. //
  34123. this.setFoveation( this.getFoveation() );
  34124. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  34125. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  34126. renderer._animation.setContext( session );
  34127. renderer._animation.start();
  34128. this.isPresenting = true;
  34129. this.dispatchEvent( { type: 'sessionstart' } );
  34130. }
  34131. }
  34132. /**
  34133. * This method is called by the renderer per frame and updates the XR camera
  34134. * and it sub cameras based on the given camera. The given camera is the "user"
  34135. * camera created on application level and used for non-XR rendering.
  34136. *
  34137. * @param {PerspectiveCamera} camera - The camera.
  34138. */
  34139. updateCamera( camera ) {
  34140. const session = this._session;
  34141. if ( session === null ) return;
  34142. const depthNear = camera.near;
  34143. const depthFar = camera.far;
  34144. const cameraXR = this._cameraXR;
  34145. const cameraL = this._cameraL;
  34146. const cameraR = this._cameraR;
  34147. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  34148. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  34149. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  34150. // Note that the new renderState won't apply until the next frame. See #18320
  34151. session.updateRenderState( {
  34152. depthNear: cameraXR.near,
  34153. depthFar: cameraXR.far
  34154. } );
  34155. this._currentDepthNear = cameraXR.near;
  34156. this._currentDepthFar = cameraXR.far;
  34157. }
  34158. cameraL.layers.mask = camera.layers.mask | 0b010;
  34159. cameraR.layers.mask = camera.layers.mask | 0b100;
  34160. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  34161. const parent = camera.parent;
  34162. const cameras = cameraXR.cameras;
  34163. updateCamera( cameraXR, parent );
  34164. for ( let i = 0; i < cameras.length; i ++ ) {
  34165. updateCamera( cameras[ i ], parent );
  34166. }
  34167. // update projection matrix for proper view frustum culling
  34168. if ( cameras.length === 2 ) {
  34169. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  34170. } else {
  34171. // assume single camera setup (AR)
  34172. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  34173. }
  34174. // update user camera and its children
  34175. updateUserCamera( camera, cameraXR, parent );
  34176. }
  34177. /**
  34178. * Returns a WebXR controller for the given controller index.
  34179. *
  34180. * @private
  34181. * @param {Number} index - The controller index.
  34182. * @return {WebXRController} The XR controller.
  34183. */
  34184. _getController( index ) {
  34185. let controller = this._controllers[ index ];
  34186. if ( controller === undefined ) {
  34187. controller = new WebXRController();
  34188. this._controllers[ index ] = controller;
  34189. }
  34190. return controller;
  34191. }
  34192. }
  34193. /**
  34194. * Assumes 2 cameras that are parallel and share an X-axis, and that
  34195. * the cameras' projection and world matrices have already been set.
  34196. * And that near and far planes are identical for both cameras.
  34197. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  34198. *
  34199. * @param {ArrayCamera} camera - The camera to update.
  34200. * @param {PerspectiveCamera} cameraL - The left camera.
  34201. * @param {PerspectiveCamera} cameraR - The right camera.
  34202. */
  34203. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  34204. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  34205. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  34206. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  34207. const projL = cameraL.projectionMatrix.elements;
  34208. const projR = cameraR.projectionMatrix.elements;
  34209. // VR systems will have identical far and near planes, and
  34210. // most likely identical top and bottom frustum extents.
  34211. // Use the left camera for these values.
  34212. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  34213. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  34214. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  34215. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  34216. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  34217. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  34218. const left = near * leftFov;
  34219. const right = near * rightFov;
  34220. // Calculate the new camera's position offset from the
  34221. // left camera. xOffset should be roughly half `ipd`.
  34222. const zOffset = ipd / ( - leftFov + rightFov );
  34223. const xOffset = zOffset * - leftFov;
  34224. // TODO: Better way to apply this offset?
  34225. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  34226. camera.translateX( xOffset );
  34227. camera.translateZ( zOffset );
  34228. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  34229. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  34230. // Check if the projection uses an infinite far plane.
  34231. if ( projL[ 10 ] === - 1.0 ) {
  34232. // Use the projection matrix from the left eye.
  34233. // The camera offset is sufficient to include the view volumes
  34234. // of both eyes (assuming symmetric projections).
  34235. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  34236. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  34237. } else {
  34238. // Find the union of the frustum values of the cameras and scale
  34239. // the values so that the near plane's position does not change in world space,
  34240. // although must now be relative to the new union camera.
  34241. const near2 = near + zOffset;
  34242. const far2 = far + zOffset;
  34243. const left2 = left - xOffset;
  34244. const right2 = right + ( ipd - xOffset );
  34245. const top2 = topFov * far / far2 * near2;
  34246. const bottom2 = bottomFov * far / far2 * near2;
  34247. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  34248. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  34249. }
  34250. }
  34251. /**
  34252. * Updates the world matrices for the given camera based on the parent 3D object.
  34253. *
  34254. * @inner
  34255. * @param {Camera} camera - The camera to update.
  34256. * @param {Object3D} parent - The parent 3D object.
  34257. */
  34258. function updateCamera( camera, parent ) {
  34259. if ( parent === null ) {
  34260. camera.matrixWorld.copy( camera.matrix );
  34261. } else {
  34262. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  34263. }
  34264. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  34265. }
  34266. /**
  34267. * Updates the given camera with the transfomration of the XR camera and parent object.
  34268. *
  34269. * @inner
  34270. * @param {Camera} camera - The camera to update.
  34271. * @param {ArrayCamera} cameraXR - The XR camera.
  34272. * @param {Object3D} parent - The parent 3D object.
  34273. */
  34274. function updateUserCamera( camera, cameraXR, parent ) {
  34275. if ( parent === null ) {
  34276. camera.matrix.copy( cameraXR.matrixWorld );
  34277. } else {
  34278. camera.matrix.copy( parent.matrixWorld );
  34279. camera.matrix.invert();
  34280. camera.matrix.multiply( cameraXR.matrixWorld );
  34281. }
  34282. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34283. camera.updateMatrixWorld( true );
  34284. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  34285. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  34286. if ( camera.isPerspectiveCamera ) {
  34287. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  34288. camera.zoom = 1;
  34289. }
  34290. }
  34291. function onSessionEvent( event ) {
  34292. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  34293. if ( controllerIndex === - 1 ) {
  34294. return;
  34295. }
  34296. const controller = this._controllers[ controllerIndex ];
  34297. if ( controller !== undefined ) {
  34298. const referenceSpace = this.getReferenceSpace();
  34299. controller.update( event.inputSource, event.frame, referenceSpace );
  34300. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  34301. }
  34302. }
  34303. function onSessionEnd() {
  34304. const session = this._session;
  34305. const renderer = this._renderer;
  34306. session.removeEventListener( 'select', this._onSessionEvent );
  34307. session.removeEventListener( 'selectstart', this._onSessionEvent );
  34308. session.removeEventListener( 'selectend', this._onSessionEvent );
  34309. session.removeEventListener( 'squeeze', this._onSessionEvent );
  34310. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  34311. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  34312. session.removeEventListener( 'end', this._onSessionEnd );
  34313. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34314. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34315. const inputSource = this._controllerInputSources[ i ];
  34316. if ( inputSource === null ) continue;
  34317. this._controllerInputSources[ i ] = null;
  34318. this._controllers[ i ].disconnect( inputSource );
  34319. }
  34320. this._currentDepthNear = null;
  34321. this._currentDepthFar = null;
  34322. // restore framebuffer/rendering state
  34323. renderer.backend.setXRTarget( null );
  34324. renderer.setRenderTarget( this._currentRenderTarget );
  34325. this._session = null;
  34326. this._xrRenderTarget = null;
  34327. //
  34328. this.isPresenting = false;
  34329. renderer._animation.stop();
  34330. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  34331. renderer._animation.setContext( this._currentAnimationContext );
  34332. renderer._animation.start();
  34333. renderer.setPixelRatio( this._currentPixelRatio );
  34334. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  34335. this.dispatchEvent( { type: 'sessionend' } );
  34336. }
  34337. function onInputSourcesChange( event ) {
  34338. const controllers = this._controllers;
  34339. const controllerInputSources = this._controllerInputSources;
  34340. // Notify disconnected
  34341. for ( let i = 0; i < event.removed.length; i ++ ) {
  34342. const inputSource = event.removed[ i ];
  34343. const index = controllerInputSources.indexOf( inputSource );
  34344. if ( index >= 0 ) {
  34345. controllerInputSources[ index ] = null;
  34346. controllers[ index ].disconnect( inputSource );
  34347. }
  34348. }
  34349. // Notify connected
  34350. for ( let i = 0; i < event.added.length; i ++ ) {
  34351. const inputSource = event.added[ i ];
  34352. let controllerIndex = controllerInputSources.indexOf( inputSource );
  34353. if ( controllerIndex === - 1 ) {
  34354. // Assign input source a controller that currently has no input source
  34355. for ( let i = 0; i < controllers.length; i ++ ) {
  34356. if ( i >= controllerInputSources.length ) {
  34357. controllerInputSources.push( inputSource );
  34358. controllerIndex = i;
  34359. break;
  34360. } else if ( controllerInputSources[ i ] === null ) {
  34361. controllerInputSources[ i ] = inputSource;
  34362. controllerIndex = i;
  34363. break;
  34364. }
  34365. }
  34366. // If all controllers do currently receive input we ignore new ones
  34367. if ( controllerIndex === - 1 ) break;
  34368. }
  34369. const controller = controllers[ controllerIndex ];
  34370. if ( controller ) {
  34371. controller.connect( inputSource );
  34372. }
  34373. }
  34374. }
  34375. function onAnimationFrame( time, frame ) {
  34376. if ( frame === undefined ) return;
  34377. const cameraXR = this._cameraXR;
  34378. const renderer = this._renderer;
  34379. const backend = renderer.backend;
  34380. const glBaseLayer = this._glBaseLayer;
  34381. const referenceSpace = this.getReferenceSpace();
  34382. const pose = frame.getViewerPose( referenceSpace );
  34383. this._xrFrame = frame;
  34384. if ( pose !== null ) {
  34385. const views = pose.views;
  34386. if ( this._glBaseLayer !== null ) {
  34387. backend.setXRTarget( glBaseLayer.framebuffer );
  34388. }
  34389. let cameraXRNeedsUpdate = false;
  34390. // check if it's necessary to rebuild cameraXR's camera list
  34391. if ( views.length !== cameraXR.cameras.length ) {
  34392. cameraXR.cameras.length = 0;
  34393. cameraXRNeedsUpdate = true;
  34394. }
  34395. for ( let i = 0; i < views.length; i ++ ) {
  34396. const view = views[ i ];
  34397. let viewport;
  34398. if ( this._useLayers === true ) {
  34399. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  34400. viewport = glSubImage.viewport;
  34401. // For side-by-side projection, we only produce a single texture for both eyes.
  34402. if ( i === 0 ) {
  34403. backend.setXRRenderTargetTextures(
  34404. this._xrRenderTarget,
  34405. glSubImage.colorTexture,
  34406. this._glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture
  34407. );
  34408. }
  34409. } else {
  34410. viewport = glBaseLayer.getViewport( view );
  34411. }
  34412. let camera = this._cameras[ i ];
  34413. if ( camera === undefined ) {
  34414. camera = new PerspectiveCamera();
  34415. camera.layers.enable( i );
  34416. camera.viewport = new Vector4();
  34417. this._cameras[ i ] = camera;
  34418. }
  34419. camera.matrix.fromArray( view.transform.matrix );
  34420. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  34421. camera.projectionMatrix.fromArray( view.projectionMatrix );
  34422. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  34423. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  34424. if ( i === 0 ) {
  34425. cameraXR.matrix.copy( camera.matrix );
  34426. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  34427. }
  34428. if ( cameraXRNeedsUpdate === true ) {
  34429. cameraXR.cameras.push( camera );
  34430. }
  34431. }
  34432. renderer.setRenderTarget( this._xrRenderTarget );
  34433. }
  34434. //
  34435. for ( let i = 0; i < this._controllers.length; i ++ ) {
  34436. const inputSource = this._controllerInputSources[ i ];
  34437. const controller = this._controllers[ i ];
  34438. if ( inputSource !== null && controller !== undefined ) {
  34439. controller.update( inputSource, frame, referenceSpace );
  34440. }
  34441. }
  34442. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  34443. if ( frame.detectedPlanes ) {
  34444. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  34445. }
  34446. this._xrFrame = null;
  34447. }
  34448. /** @module Renderer **/
  34449. const _scene = /*@__PURE__*/ new Scene();
  34450. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  34451. const _screen = /*@__PURE__*/ new Vector4();
  34452. const _frustum = /*@__PURE__*/ new Frustum();
  34453. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  34454. const _vector4 = /*@__PURE__*/ new Vector4();
  34455. /**
  34456. * Base class for renderers.
  34457. */
  34458. class Renderer {
  34459. /**
  34460. * Constructs a new renderer.
  34461. *
  34462. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  34463. * @param {Object} parameters - The configuration parameter.
  34464. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  34465. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  34466. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  34467. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  34468. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  34469. * @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
  34470. * to overwrite the default.
  34471. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34472. * @param {Number} [parameters.colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  34473. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  34474. */
  34475. constructor( backend, parameters = {} ) {
  34476. /**
  34477. * This flag can be used for type testing.
  34478. *
  34479. * @type {Boolean}
  34480. * @readonly
  34481. * @default true
  34482. */
  34483. this.isRenderer = true;
  34484. //
  34485. const {
  34486. logarithmicDepthBuffer = false,
  34487. alpha = true,
  34488. depth = true,
  34489. stencil = false,
  34490. antialias = false,
  34491. samples = 0,
  34492. getFallback = null,
  34493. colorBufferType = HalfFloatType
  34494. } = parameters;
  34495. /**
  34496. * A reference to the canvas element the renderer is drawing to.
  34497. * This value of this property will automatically be created by
  34498. * the renderer.
  34499. *
  34500. * @type {HTMLCanvasElement|OffscreenCanvas}
  34501. */
  34502. this.domElement = backend.getDomElement();
  34503. /**
  34504. * A reference to the current backend.
  34505. *
  34506. * @type {Backend}
  34507. */
  34508. this.backend = backend;
  34509. /**
  34510. * The number of MSAA samples.
  34511. *
  34512. * @type {Number}
  34513. * @default 0
  34514. */
  34515. this.samples = samples || ( antialias === true ) ? 4 : 0;
  34516. /**
  34517. * Whether the renderer should automatically clear the current rendering target
  34518. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  34519. * or the current bound render target (custom framebuffer).
  34520. *
  34521. * @type {Boolean}
  34522. * @default true
  34523. */
  34524. this.autoClear = true;
  34525. /**
  34526. * When `autoClear` is set to `true`, this property defines whether the renderer
  34527. * should clear the color buffer.
  34528. *
  34529. * @type {Boolean}
  34530. * @default true
  34531. */
  34532. this.autoClearColor = true;
  34533. /**
  34534. * When `autoClear` is set to `true`, this property defines whether the renderer
  34535. * should clear the depth buffer.
  34536. *
  34537. * @type {Boolean}
  34538. * @default true
  34539. */
  34540. this.autoClearDepth = true;
  34541. /**
  34542. * When `autoClear` is set to `true`, this property defines whether the renderer
  34543. * should clear the stencil buffer.
  34544. *
  34545. * @type {Boolean}
  34546. * @default true
  34547. */
  34548. this.autoClearStencil = true;
  34549. /**
  34550. * Whether the default framebuffer should be transparent or opaque.
  34551. *
  34552. * @type {Boolean}
  34553. * @default true
  34554. */
  34555. this.alpha = alpha;
  34556. /**
  34557. * Whether logarithmic depth buffer is enabled or not.
  34558. *
  34559. * @type {Boolean}
  34560. * @default false
  34561. */
  34562. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  34563. /**
  34564. * Defines the output color space of the renderer.
  34565. *
  34566. * @type {String}
  34567. * @default SRGBColorSpace
  34568. */
  34569. this.outputColorSpace = SRGBColorSpace;
  34570. /**
  34571. * Defines the tone mapping of the renderer.
  34572. *
  34573. * @type {Number}
  34574. * @default NoToneMapping
  34575. */
  34576. this.toneMapping = NoToneMapping;
  34577. /**
  34578. * Defines the tone mapping exposure.
  34579. *
  34580. * @type {Number}
  34581. * @default 1
  34582. */
  34583. this.toneMappingExposure = 1.0;
  34584. /**
  34585. * Whether the renderer should sort its render lists or not.
  34586. *
  34587. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  34588. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  34589. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  34590. * e.g. manually determining each object's rendering order.
  34591. *
  34592. * @type {Boolean}
  34593. * @default true
  34594. */
  34595. this.sortObjects = true;
  34596. /**
  34597. * Whether the default framebuffer should have a depth buffer or not.
  34598. *
  34599. * @type {Boolean}
  34600. * @default true
  34601. */
  34602. this.depth = depth;
  34603. /**
  34604. * Whether the default framebuffer should have a stencil buffer or not.
  34605. *
  34606. * @type {Boolean}
  34607. * @default false
  34608. */
  34609. this.stencil = stencil;
  34610. /**
  34611. * Holds a series of statistical information about the GPU memory
  34612. * and the rendering process. Useful for debugging and monitoring.
  34613. *
  34614. * @type {Info}
  34615. */
  34616. this.info = new Info();
  34617. this.nodes = {
  34618. modelViewMatrix: null,
  34619. modelNormalViewMatrix: null
  34620. };
  34621. /**
  34622. * The node library defines how certain library objects like materials, lights
  34623. * or tone mapping functions are mapped to node types. This is required since
  34624. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  34625. * be part of the scene graph, they are internally represented as nodes for
  34626. * further processing.
  34627. *
  34628. * @type {NodeLibrary}
  34629. */
  34630. this.library = new NodeLibrary();
  34631. /**
  34632. * A map-like data structure for managing lights.
  34633. *
  34634. * @type {Lighting}
  34635. */
  34636. this.lighting = new Lighting();
  34637. // internals
  34638. /**
  34639. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  34640. *
  34641. * @private
  34642. * @type {Function}
  34643. */
  34644. this._getFallback = getFallback;
  34645. /**
  34646. * The renderer's pixel ration.
  34647. *
  34648. * @private
  34649. * @type {Number}
  34650. * @default 1
  34651. */
  34652. this._pixelRatio = 1;
  34653. /**
  34654. * The width of the renderer's default framebuffer in logical pixel unit.
  34655. *
  34656. * @private
  34657. * @type {Number}
  34658. */
  34659. this._width = this.domElement.width;
  34660. /**
  34661. * The height of the renderer's default framebuffer in logical pixel unit.
  34662. *
  34663. * @private
  34664. * @type {Number}
  34665. */
  34666. this._height = this.domElement.height;
  34667. /**
  34668. * The viewport of the renderer in logical pixel unit.
  34669. *
  34670. * @private
  34671. * @type {Vector4}
  34672. */
  34673. this._viewport = new Vector4( 0, 0, this._width, this._height );
  34674. /**
  34675. * The scissor rectangle of the renderer in logical pixel unit.
  34676. *
  34677. * @private
  34678. * @type {Vector4}
  34679. */
  34680. this._scissor = new Vector4( 0, 0, this._width, this._height );
  34681. /**
  34682. * Whether the scissor test should be enabled or not.
  34683. *
  34684. * @private
  34685. * @type {Boolean}
  34686. */
  34687. this._scissorTest = false;
  34688. /**
  34689. * A reference to a renderer module for managing shader attributes.
  34690. *
  34691. * @private
  34692. * @type {Attributes?}
  34693. * @default null
  34694. */
  34695. this._attributes = null;
  34696. /**
  34697. * A reference to a renderer module for managing geometries.
  34698. *
  34699. * @private
  34700. * @type {Geometries?}
  34701. * @default null
  34702. */
  34703. this._geometries = null;
  34704. /**
  34705. * A reference to a renderer module for managing node related logic.
  34706. *
  34707. * @private
  34708. * @type {Nodes?}
  34709. * @default null
  34710. */
  34711. this._nodes = null;
  34712. /**
  34713. * A reference to a renderer module for managing the internal animation loop.
  34714. *
  34715. * @private
  34716. * @type {Animation?}
  34717. * @default null
  34718. */
  34719. this._animation = null;
  34720. /**
  34721. * A reference to a renderer module for managing shader program bindings.
  34722. *
  34723. * @private
  34724. * @type {Bindings?}
  34725. * @default null
  34726. */
  34727. this._bindings = null;
  34728. /**
  34729. * A reference to a renderer module for managing render objects.
  34730. *
  34731. * @private
  34732. * @type {RenderObjects?}
  34733. * @default null
  34734. */
  34735. this._objects = null;
  34736. /**
  34737. * A reference to a renderer module for managing render and compute pipelines.
  34738. *
  34739. * @private
  34740. * @type {Pipelines?}
  34741. * @default null
  34742. */
  34743. this._pipelines = null;
  34744. /**
  34745. * A reference to a renderer module for managing render bundles.
  34746. *
  34747. * @private
  34748. * @type {RenderBundles?}
  34749. * @default null
  34750. */
  34751. this._bundles = null;
  34752. /**
  34753. * A reference to a renderer module for managing render lists.
  34754. *
  34755. * @private
  34756. * @type {RenderLists?}
  34757. * @default null
  34758. */
  34759. this._renderLists = null;
  34760. /**
  34761. * A reference to a renderer module for managing render contexts.
  34762. *
  34763. * @private
  34764. * @type {RenderContexts?}
  34765. * @default null
  34766. */
  34767. this._renderContexts = null;
  34768. /**
  34769. * A reference to a renderer module for managing textures.
  34770. *
  34771. * @private
  34772. * @type {Textures?}
  34773. * @default null
  34774. */
  34775. this._textures = null;
  34776. /**
  34777. * A reference to a renderer module for backgrounds.
  34778. *
  34779. * @private
  34780. * @type {Background?}
  34781. * @default null
  34782. */
  34783. this._background = null;
  34784. /**
  34785. * This fullscreen quad is used for internal render passes
  34786. * like the tone mapping and color space output pass.
  34787. *
  34788. * @private
  34789. * @type {QuadMesh}
  34790. */
  34791. this._quad = new QuadMesh( new NodeMaterial() );
  34792. this._quad.material.name = 'Renderer_output';
  34793. /**
  34794. * A reference to the current render context.
  34795. *
  34796. * @private
  34797. * @type {RenderContext?}
  34798. * @default null
  34799. */
  34800. this._currentRenderContext = null;
  34801. /**
  34802. * A custom sort function for the opaque render list.
  34803. *
  34804. * @private
  34805. * @type {Function?}
  34806. * @default null
  34807. */
  34808. this._opaqueSort = null;
  34809. /**
  34810. * A custom sort function for the transparent render list.
  34811. *
  34812. * @private
  34813. * @type {Function?}
  34814. * @default null
  34815. */
  34816. this._transparentSort = null;
  34817. /**
  34818. * The framebuffer target.
  34819. *
  34820. * @private
  34821. * @type {RenderTarget?}
  34822. * @default null
  34823. */
  34824. this._frameBufferTarget = null;
  34825. const alphaClear = this.alpha === true ? 0 : 1;
  34826. /**
  34827. * The clear color value.
  34828. *
  34829. * @private
  34830. * @type {Color4}
  34831. */
  34832. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  34833. /**
  34834. * The clear depth value.
  34835. *
  34836. * @private
  34837. * @type {Number}
  34838. * @default 1
  34839. */
  34840. this._clearDepth = 1;
  34841. /**
  34842. * The clear stencil value.
  34843. *
  34844. * @private
  34845. * @type {Number}
  34846. * @default 0
  34847. */
  34848. this._clearStencil = 0;
  34849. /**
  34850. * The current render target.
  34851. *
  34852. * @private
  34853. * @type {RenderTarget?}
  34854. * @default null
  34855. */
  34856. this._renderTarget = null;
  34857. /**
  34858. * The active cube face.
  34859. *
  34860. * @private
  34861. * @type {Number}
  34862. * @default 0
  34863. */
  34864. this._activeCubeFace = 0;
  34865. /**
  34866. * The active mipmap level.
  34867. *
  34868. * @private
  34869. * @type {Number}
  34870. * @default 0
  34871. */
  34872. this._activeMipmapLevel = 0;
  34873. /**
  34874. * The MRT setting.
  34875. *
  34876. * @private
  34877. * @type {MRTNode?}
  34878. * @default null
  34879. */
  34880. this._mrt = null;
  34881. /**
  34882. * This function defines how a render object is going
  34883. * to be rendered.
  34884. *
  34885. * @private
  34886. * @type {Function?}
  34887. * @default null
  34888. */
  34889. this._renderObjectFunction = null;
  34890. /**
  34891. * Used to keep track of the current render object function.
  34892. *
  34893. * @private
  34894. * @type {Function?}
  34895. * @default null
  34896. */
  34897. this._currentRenderObjectFunction = null;
  34898. /**
  34899. * Used to keep track of the current render bundle.
  34900. *
  34901. * @private
  34902. * @type {RenderBundle?}
  34903. * @default null
  34904. */
  34905. this._currentRenderBundle = null;
  34906. /**
  34907. * Next to `_renderObjectFunction()`, this function provides another hook
  34908. * for influencing the render process of a render object. It is meant for internal
  34909. * use and only relevant for `compileAsync()` right now. Instead of using
  34910. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  34911. * a different function might be used which performs no draw but just the node
  34912. * and pipeline updates.
  34913. *
  34914. * @private
  34915. * @type {Function?}
  34916. * @default null
  34917. */
  34918. this._handleObjectFunction = this._renderObjectDirect;
  34919. /**
  34920. * Indicates whether the device has been lost or not. In WebGL terms, the device
  34921. * lost is considered as a context lost. When this is set to `true`, rendering
  34922. * isn't possible anymore.
  34923. *
  34924. * @private
  34925. * @type {Boolean}
  34926. * @default false
  34927. */
  34928. this._isDeviceLost = false;
  34929. /**
  34930. * A callback function that defines what should happen when a device/context lost occurs.
  34931. *
  34932. * @type {Function}
  34933. */
  34934. this.onDeviceLost = this._onDeviceLost;
  34935. /**
  34936. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  34937. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  34938. * This will reduce rendering quality though.
  34939. *
  34940. * @private
  34941. * @type {Number}
  34942. * @default HalfFloatType
  34943. */
  34944. this._colorBufferType = colorBufferType;
  34945. /**
  34946. * Whether the renderer has been initialized or not.
  34947. *
  34948. * @private
  34949. * @type {Boolean}
  34950. * @default false
  34951. */
  34952. this._initialized = false;
  34953. /**
  34954. * A reference to the promise which initializes the renderer.
  34955. *
  34956. * @private
  34957. * @type {Promise?}
  34958. * @default null
  34959. */
  34960. this._initPromise = null;
  34961. /**
  34962. * An array of compilation promises which are used in `compileAsync()`.
  34963. *
  34964. * @private
  34965. * @type {Array<Promise>?}
  34966. * @default null
  34967. */
  34968. this._compilationPromises = null;
  34969. /**
  34970. * Whether the renderer should render transparent render objects or not.
  34971. *
  34972. * @type {Boolean}
  34973. * @default true
  34974. */
  34975. this.transparent = true;
  34976. /**
  34977. * Whether the renderer should render opaque render objects or not.
  34978. *
  34979. * @type {Boolean}
  34980. * @default true
  34981. */
  34982. this.opaque = true;
  34983. /**
  34984. * Shadow map configuration
  34985. * @typedef {Object} ShadowMapConfig
  34986. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  34987. * @property {Number} type - The shadow map type.
  34988. */
  34989. /**
  34990. * The renderer's shadow configuration.
  34991. *
  34992. * @type {module:Renderer~ShadowMapConfig}
  34993. */
  34994. this.shadowMap = {
  34995. enabled: false,
  34996. type: PCFShadowMap
  34997. };
  34998. /**
  34999. * XR configuration.
  35000. * @typedef {Object} XRConfig
  35001. * @property {Boolean} enabled - Whether to globally enable XR or not.
  35002. */
  35003. /**
  35004. * The renderer's XR manager.
  35005. *
  35006. * @type {XRManager}
  35007. */
  35008. this.xr = new XRManager( this );
  35009. /**
  35010. * Debug configuration.
  35011. * @typedef {Object} DebugConfig
  35012. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  35013. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  35014. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  35015. */
  35016. /**
  35017. * The renderer's debug configuration.
  35018. *
  35019. * @type {module:Renderer~DebugConfig}
  35020. */
  35021. this.debug = {
  35022. checkShaderErrors: true,
  35023. onShaderError: null,
  35024. getShaderAsync: async ( scene, camera, object ) => {
  35025. await this.compileAsync( scene, camera );
  35026. const renderList = this._renderLists.get( scene, camera );
  35027. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  35028. const material = scene.overrideMaterial || object.material;
  35029. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  35030. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  35031. return { fragmentShader, vertexShader };
  35032. }
  35033. };
  35034. }
  35035. /**
  35036. * Initializes the renderer so it is ready for usage.
  35037. *
  35038. * @async
  35039. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  35040. */
  35041. async init() {
  35042. if ( this._initialized ) {
  35043. throw new Error( 'Renderer: Backend has already been initialized.' );
  35044. }
  35045. if ( this._initPromise !== null ) {
  35046. return this._initPromise;
  35047. }
  35048. this._initPromise = new Promise( async ( resolve, reject ) => {
  35049. let backend = this.backend;
  35050. try {
  35051. await backend.init( this );
  35052. } catch ( error ) {
  35053. if ( this._getFallback !== null ) {
  35054. // try the fallback
  35055. try {
  35056. this.backend = backend = this._getFallback( error );
  35057. await backend.init( this );
  35058. } catch ( error ) {
  35059. reject( error );
  35060. return;
  35061. }
  35062. } else {
  35063. reject( error );
  35064. return;
  35065. }
  35066. }
  35067. this._nodes = new Nodes( this, backend );
  35068. this._animation = new Animation( this._nodes, this.info );
  35069. this._attributes = new Attributes( backend );
  35070. this._background = new Background( this, this._nodes );
  35071. this._geometries = new Geometries( this._attributes, this.info );
  35072. this._textures = new Textures( this, backend, this.info );
  35073. this._pipelines = new Pipelines( backend, this._nodes );
  35074. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35075. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35076. this._renderLists = new RenderLists( this.lighting );
  35077. this._bundles = new RenderBundles();
  35078. this._renderContexts = new RenderContexts();
  35079. //
  35080. this._animation.start();
  35081. this._initialized = true;
  35082. resolve();
  35083. } );
  35084. return this._initPromise;
  35085. }
  35086. /**
  35087. * The coordinate system of the renderer. The value of this property
  35088. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  35089. * `THREE.WebGPUCoordinateSystem`.
  35090. *
  35091. * @readonly
  35092. * @type {Number}
  35093. */
  35094. get coordinateSystem() {
  35095. return this.backend.coordinateSystem;
  35096. }
  35097. /**
  35098. * Compiles all materials in the given scene. This can be useful to avoid a
  35099. * phenomenon which is called "shader compilation stutter", which occurs when
  35100. * rendering an object with a new shader for the first time.
  35101. *
  35102. * If you want to add a 3D object to an existing scene, use the third optional
  35103. * parameter for applying the target scene. Note that the (target) scene's lighting
  35104. * and environment must be configured before calling this method.
  35105. *
  35106. * @async
  35107. * @param {Object3D} scene - The scene or 3D object to precompile.
  35108. * @param {Camera} camera - The camera that is used to render the scene.
  35109. * @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.
  35110. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  35111. */
  35112. async compileAsync( scene, camera, targetScene = null ) {
  35113. if ( this._isDeviceLost === true ) return;
  35114. if ( this._initialized === false ) await this.init();
  35115. // preserve render tree
  35116. const nodeFrame = this._nodes.nodeFrame;
  35117. const previousRenderId = nodeFrame.renderId;
  35118. const previousRenderContext = this._currentRenderContext;
  35119. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35120. const previousCompilationPromises = this._compilationPromises;
  35121. //
  35122. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35123. if ( targetScene === null ) targetScene = scene;
  35124. const renderTarget = this._renderTarget;
  35125. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  35126. const activeMipmapLevel = this._activeMipmapLevel;
  35127. const compilationPromises = [];
  35128. this._currentRenderContext = renderContext;
  35129. this._currentRenderObjectFunction = this.renderObject;
  35130. this._handleObjectFunction = this._createObjectPipeline;
  35131. this._compilationPromises = compilationPromises;
  35132. nodeFrame.renderId ++;
  35133. //
  35134. nodeFrame.update();
  35135. //
  35136. renderContext.depth = this.depth;
  35137. renderContext.stencil = this.stencil;
  35138. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35139. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  35140. //
  35141. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35142. //
  35143. const renderList = this._renderLists.get( scene, camera );
  35144. renderList.begin();
  35145. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  35146. // include lights from target scene
  35147. if ( targetScene !== scene ) {
  35148. targetScene.traverseVisible( function ( object ) {
  35149. if ( object.isLight && object.layers.test( camera.layers ) ) {
  35150. renderList.pushLight( object );
  35151. }
  35152. } );
  35153. }
  35154. renderList.finish();
  35155. //
  35156. if ( renderTarget !== null ) {
  35157. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35158. const renderTargetData = this._textures.get( renderTarget );
  35159. renderContext.textures = renderTargetData.textures;
  35160. renderContext.depthTexture = renderTargetData.depthTexture;
  35161. } else {
  35162. renderContext.textures = null;
  35163. renderContext.depthTexture = null;
  35164. }
  35165. //
  35166. this._background.update( sceneRef, renderList, renderContext );
  35167. // process render lists
  35168. const opaqueObjects = renderList.opaque;
  35169. const transparentObjects = renderList.transparent;
  35170. const transparentDoublePassObjects = renderList.transparentDoublePass;
  35171. const lightsNode = renderList.lightsNode;
  35172. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35173. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  35174. // restore render tree
  35175. nodeFrame.renderId = previousRenderId;
  35176. this._currentRenderContext = previousRenderContext;
  35177. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35178. this._compilationPromises = previousCompilationPromises;
  35179. this._handleObjectFunction = this._renderObjectDirect;
  35180. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  35181. await Promise.all( compilationPromises );
  35182. }
  35183. /**
  35184. * Renders the scene in an async fashion.
  35185. *
  35186. * @async
  35187. * @param {Object3D} scene - The scene or 3D object to render.
  35188. * @param {Camera} camera - The camera.
  35189. * @return {Promise} A Promise that resolves when the render has been finished.
  35190. */
  35191. async renderAsync( scene, camera ) {
  35192. if ( this._initialized === false ) await this.init();
  35193. this._renderScene( scene, camera );
  35194. }
  35195. /**
  35196. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  35197. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  35198. *
  35199. * @async
  35200. * @return {Promise} A Promise that resolves when synchronization has been finished.
  35201. */
  35202. async waitForGPU() {
  35203. await this.backend.waitForGPU();
  35204. }
  35205. /**
  35206. * Sets the given MRT configuration.
  35207. *
  35208. * @param {MRTNode} mrt - The MRT node to set.
  35209. * @return {Renderer} A reference to this renderer.
  35210. */
  35211. setMRT( mrt ) {
  35212. this._mrt = mrt;
  35213. return this;
  35214. }
  35215. /**
  35216. * Returns the MRT configuration.
  35217. *
  35218. * @return {MRTNode} The MRT configuration.
  35219. */
  35220. getMRT() {
  35221. return this._mrt;
  35222. }
  35223. /**
  35224. * Returns the color buffer type.
  35225. *
  35226. * @return {Number} The color buffer type.
  35227. */
  35228. getColorBufferType() {
  35229. return this._colorBufferType;
  35230. }
  35231. /**
  35232. * Default implementation of the device lost callback.
  35233. *
  35234. * @private
  35235. * @param {Object} info - Information about the context lost.
  35236. */
  35237. _onDeviceLost( info ) {
  35238. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  35239. if ( info.reason ) {
  35240. errorMessage += `\nReason: ${info.reason}`;
  35241. }
  35242. console.error( errorMessage );
  35243. this._isDeviceLost = true;
  35244. }
  35245. /**
  35246. * Renders the given render bundle.
  35247. *
  35248. * @private
  35249. * @param {Object} bundle - Render bundle data.
  35250. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  35251. * @param {LightsNode} lightsNode - The current lights node.
  35252. */
  35253. _renderBundle( bundle, sceneRef, lightsNode ) {
  35254. const { bundleGroup, camera, renderList } = bundle;
  35255. const renderContext = this._currentRenderContext;
  35256. //
  35257. const renderBundle = this._bundles.get( bundleGroup, camera );
  35258. const renderBundleData = this.backend.get( renderBundle );
  35259. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  35260. //
  35261. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  35262. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  35263. renderBundleData.renderContexts.add( renderContext );
  35264. if ( renderBundleNeedsUpdate ) {
  35265. this.backend.beginBundle( renderContext );
  35266. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  35267. renderBundleData.renderObjects = [];
  35268. }
  35269. this._currentRenderBundle = renderBundle;
  35270. const opaqueObjects = renderList.opaque;
  35271. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35272. this._currentRenderBundle = null;
  35273. //
  35274. this.backend.finishBundle( renderContext, renderBundle );
  35275. renderBundleData.version = bundleGroup.version;
  35276. } else {
  35277. const { renderObjects } = renderBundleData;
  35278. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  35279. const renderObject = renderObjects[ i ];
  35280. if ( this._nodes.needsRefresh( renderObject ) ) {
  35281. this._nodes.updateBefore( renderObject );
  35282. this._nodes.updateForRender( renderObject );
  35283. this._bindings.updateForRender( renderObject );
  35284. this._nodes.updateAfter( renderObject );
  35285. }
  35286. }
  35287. }
  35288. this.backend.addBundle( renderContext, renderBundle );
  35289. }
  35290. /**
  35291. * Renders the scene or 3D object with the given camera. This method can only be called
  35292. * if the renderer has been initialized.
  35293. *
  35294. * The target of the method is the default framebuffer (meaning the canvas)
  35295. * or alternatively a render target when specified via `setRenderTarget()`.
  35296. *
  35297. * @param {Object3D} scene - The scene or 3D object to render.
  35298. * @param {Camera} camera - The camera to render the scene with.
  35299. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  35300. * Only returned when the renderer has not been initialized.
  35301. */
  35302. render( scene, camera ) {
  35303. if ( this._initialized === false ) {
  35304. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  35305. return this.renderAsync( scene, camera );
  35306. }
  35307. this._renderScene( scene, camera );
  35308. }
  35309. /**
  35310. * Returns an internal render target which is used when computing the output tone mapping
  35311. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  35312. * pass and not inline to achieve more correct results.
  35313. *
  35314. * @private
  35315. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  35316. */
  35317. _getFrameBufferTarget() {
  35318. const { currentToneMapping, currentColorSpace } = this;
  35319. const useToneMapping = currentToneMapping !== NoToneMapping;
  35320. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  35321. if ( useToneMapping === false && useColorSpace === false ) return null;
  35322. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  35323. const { depth, stencil } = this;
  35324. let frameBufferTarget = this._frameBufferTarget;
  35325. if ( frameBufferTarget === null ) {
  35326. frameBufferTarget = new RenderTarget( width, height, {
  35327. depthBuffer: depth,
  35328. stencilBuffer: stencil,
  35329. type: this._colorBufferType,
  35330. format: RGBAFormat,
  35331. colorSpace: LinearSRGBColorSpace,
  35332. generateMipmaps: false,
  35333. minFilter: LinearFilter,
  35334. magFilter: LinearFilter,
  35335. samples: this.samples
  35336. } );
  35337. frameBufferTarget.isPostProcessingRenderTarget = true;
  35338. this._frameBufferTarget = frameBufferTarget;
  35339. }
  35340. frameBufferTarget.depthBuffer = depth;
  35341. frameBufferTarget.stencilBuffer = stencil;
  35342. frameBufferTarget.setSize( width, height );
  35343. frameBufferTarget.viewport.copy( this._viewport );
  35344. frameBufferTarget.scissor.copy( this._scissor );
  35345. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  35346. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  35347. frameBufferTarget.scissorTest = this._scissorTest;
  35348. return frameBufferTarget;
  35349. }
  35350. /**
  35351. * Renders the scene or 3D object with the given camera.
  35352. *
  35353. * @private
  35354. * @param {Object3D} scene - The scene or 3D object to render.
  35355. * @param {Camera} camera - The camera to render the scene with.
  35356. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  35357. * @return {RenderContext} The current render context.
  35358. */
  35359. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  35360. if ( this._isDeviceLost === true ) return;
  35361. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  35362. // preserve render tree
  35363. const nodeFrame = this._nodes.nodeFrame;
  35364. const previousRenderId = nodeFrame.renderId;
  35365. const previousRenderContext = this._currentRenderContext;
  35366. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  35367. //
  35368. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  35369. const outputRenderTarget = this._renderTarget;
  35370. const activeCubeFace = this._activeCubeFace;
  35371. const activeMipmapLevel = this._activeMipmapLevel;
  35372. //
  35373. let renderTarget;
  35374. if ( frameBufferTarget !== null ) {
  35375. renderTarget = frameBufferTarget;
  35376. this.setRenderTarget( renderTarget );
  35377. } else {
  35378. renderTarget = outputRenderTarget;
  35379. }
  35380. //
  35381. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  35382. this._currentRenderContext = renderContext;
  35383. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  35384. //
  35385. this.info.calls ++;
  35386. this.info.render.calls ++;
  35387. this.info.render.frameCalls ++;
  35388. nodeFrame.renderId = this.info.calls;
  35389. //
  35390. const coordinateSystem = this.coordinateSystem;
  35391. const xr = this.xr;
  35392. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  35393. camera.coordinateSystem = coordinateSystem;
  35394. camera.updateProjectionMatrix();
  35395. if ( camera.isArrayCamera ) {
  35396. for ( const subCamera of camera.cameras ) {
  35397. subCamera.coordinateSystem = coordinateSystem;
  35398. subCamera.updateProjectionMatrix();
  35399. }
  35400. }
  35401. }
  35402. //
  35403. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  35404. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  35405. if ( xr.enabled === true && xr.isPresenting === true ) {
  35406. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  35407. camera = xr.getCamera(); // use XR camera for rendering
  35408. }
  35409. //
  35410. let viewport = this._viewport;
  35411. let scissor = this._scissor;
  35412. let pixelRatio = this._pixelRatio;
  35413. if ( renderTarget !== null ) {
  35414. viewport = renderTarget.viewport;
  35415. scissor = renderTarget.scissor;
  35416. pixelRatio = 1;
  35417. }
  35418. this.getDrawingBufferSize( _drawingBufferSize );
  35419. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  35420. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  35421. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  35422. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  35423. renderContext.viewportValue.width >>= activeMipmapLevel;
  35424. renderContext.viewportValue.height >>= activeMipmapLevel;
  35425. renderContext.viewportValue.minDepth = minDepth;
  35426. renderContext.viewportValue.maxDepth = maxDepth;
  35427. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  35428. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  35429. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  35430. renderContext.scissorValue.width >>= activeMipmapLevel;
  35431. renderContext.scissorValue.height >>= activeMipmapLevel;
  35432. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  35433. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  35434. //
  35435. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  35436. //
  35437. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  35438. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  35439. const renderList = this._renderLists.get( scene, camera );
  35440. renderList.begin();
  35441. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  35442. renderList.finish();
  35443. if ( this.sortObjects === true ) {
  35444. renderList.sort( this._opaqueSort, this._transparentSort );
  35445. }
  35446. //
  35447. if ( renderTarget !== null ) {
  35448. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  35449. const renderTargetData = this._textures.get( renderTarget );
  35450. renderContext.textures = renderTargetData.textures;
  35451. renderContext.depthTexture = renderTargetData.depthTexture;
  35452. renderContext.width = renderTargetData.width;
  35453. renderContext.height = renderTargetData.height;
  35454. renderContext.renderTarget = renderTarget;
  35455. renderContext.depth = renderTarget.depthBuffer;
  35456. renderContext.stencil = renderTarget.stencilBuffer;
  35457. } else {
  35458. renderContext.textures = null;
  35459. renderContext.depthTexture = null;
  35460. renderContext.width = this.domElement.width;
  35461. renderContext.height = this.domElement.height;
  35462. renderContext.depth = this.depth;
  35463. renderContext.stencil = this.stencil;
  35464. }
  35465. renderContext.width >>= activeMipmapLevel;
  35466. renderContext.height >>= activeMipmapLevel;
  35467. renderContext.activeCubeFace = activeCubeFace;
  35468. renderContext.activeMipmapLevel = activeMipmapLevel;
  35469. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  35470. //
  35471. this._background.update( sceneRef, renderList, renderContext );
  35472. //
  35473. this.backend.beginRender( renderContext );
  35474. // process render lists
  35475. const {
  35476. bundles,
  35477. lightsNode,
  35478. transparentDoublePass: transparentDoublePassObjects,
  35479. transparent: transparentObjects,
  35480. opaque: opaqueObjects
  35481. } = renderList;
  35482. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  35483. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  35484. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  35485. // finish render pass
  35486. this.backend.finishRender( renderContext );
  35487. // restore render tree
  35488. nodeFrame.renderId = previousRenderId;
  35489. this._currentRenderContext = previousRenderContext;
  35490. this._currentRenderObjectFunction = previousRenderObjectFunction;
  35491. //
  35492. if ( frameBufferTarget !== null ) {
  35493. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  35494. const quad = this._quad;
  35495. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35496. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35497. quad.material.needsUpdate = true;
  35498. }
  35499. this._renderScene( quad, quad.camera, false );
  35500. }
  35501. //
  35502. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  35503. //
  35504. return renderContext;
  35505. }
  35506. /**
  35507. * Returns the maximum available anisotropy for texture filtering.
  35508. *
  35509. * @return {Number} The maximum available anisotropy.
  35510. */
  35511. getMaxAnisotropy() {
  35512. return this.backend.getMaxAnisotropy();
  35513. }
  35514. /**
  35515. * Returns the active cube face.
  35516. *
  35517. * @return {Number} The active cube face.
  35518. */
  35519. getActiveCubeFace() {
  35520. return this._activeCubeFace;
  35521. }
  35522. /**
  35523. * Returns the active mipmap level.
  35524. *
  35525. * @return {Number} The active mipmap level.
  35526. */
  35527. getActiveMipmapLevel() {
  35528. return this._activeMipmapLevel;
  35529. }
  35530. /**
  35531. * Applications are advised to always define the animation loop
  35532. * with this method and not manually with `requestAnimationFrame()`
  35533. * for best compatibility.
  35534. *
  35535. * @async
  35536. * @param {Function} callback - The application's animation loop.
  35537. * @return {Promise} A Promise that resolves when the set has been executed.
  35538. */
  35539. async setAnimationLoop( callback ) {
  35540. if ( this._initialized === false ) await this.init();
  35541. this._animation.setAnimationLoop( callback );
  35542. }
  35543. /**
  35544. * Can be used to transfer buffer data from a storage buffer attribute
  35545. * from the GPU to the CPU in context of compute shaders.
  35546. *
  35547. * @async
  35548. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  35549. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  35550. */
  35551. async getArrayBufferAsync( attribute ) {
  35552. return await this.backend.getArrayBufferAsync( attribute );
  35553. }
  35554. /**
  35555. * Returns the rendering context.
  35556. *
  35557. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  35558. */
  35559. getContext() {
  35560. return this.backend.getContext();
  35561. }
  35562. /**
  35563. * Returns the pixel ratio.
  35564. *
  35565. * @return {Number} The pixel ratio.
  35566. */
  35567. getPixelRatio() {
  35568. return this._pixelRatio;
  35569. }
  35570. /**
  35571. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  35572. *
  35573. * @param {Vector2} target - The method writes the result in this target object.
  35574. * @return {Vector2} The drawing buffer size.
  35575. */
  35576. getDrawingBufferSize( target ) {
  35577. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  35578. }
  35579. /**
  35580. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  35581. *
  35582. * @param {Vector2} target - The method writes the result in this target object.
  35583. * @return {Vector2} The drawing buffer size.
  35584. */
  35585. getSize( target ) {
  35586. return target.set( this._width, this._height );
  35587. }
  35588. /**
  35589. * Sets the given pixel ration and resizes the canvas if necessary.
  35590. *
  35591. * @param {Number} [value=1] - The pixel ratio.
  35592. */
  35593. setPixelRatio( value = 1 ) {
  35594. if ( this._pixelRatio === value ) return;
  35595. this._pixelRatio = value;
  35596. this.setSize( this._width, this._height, false );
  35597. }
  35598. /**
  35599. * This method allows to define the drawing buffer size by specifying
  35600. * width, height and pixel ratio all at once. The size of the drawing
  35601. * buffer is computed with this formula:
  35602. * ````
  35603. * size.x = width * pixelRatio;
  35604. * size.y = height * pixelRatio;
  35605. *```
  35606. *
  35607. * @param {Number} width - The width in logical pixels.
  35608. * @param {Number} height - The height in logical pixels.
  35609. * @param {Number} pixelRatio - The pixel ratio.
  35610. */
  35611. setDrawingBufferSize( width, height, pixelRatio ) {
  35612. this._width = width;
  35613. this._height = height;
  35614. this._pixelRatio = pixelRatio;
  35615. this.domElement.width = Math.floor( width * pixelRatio );
  35616. this.domElement.height = Math.floor( height * pixelRatio );
  35617. this.setViewport( 0, 0, width, height );
  35618. if ( this._initialized ) this.backend.updateSize();
  35619. }
  35620. /**
  35621. * Sets the size of the renderer.
  35622. *
  35623. * @param {Number} width - The width in logical pixels.
  35624. * @param {Number} height - The height in logical pixels.
  35625. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  35626. */
  35627. setSize( width, height, updateStyle = true ) {
  35628. this._width = width;
  35629. this._height = height;
  35630. this.domElement.width = Math.floor( width * this._pixelRatio );
  35631. this.domElement.height = Math.floor( height * this._pixelRatio );
  35632. if ( updateStyle === true ) {
  35633. this.domElement.style.width = width + 'px';
  35634. this.domElement.style.height = height + 'px';
  35635. }
  35636. this.setViewport( 0, 0, width, height );
  35637. if ( this._initialized ) this.backend.updateSize();
  35638. }
  35639. /**
  35640. * Defines a manual sort function for the opaque render list.
  35641. * Pass `null` to use the default sort.
  35642. *
  35643. * @param {Function} method - The sort function.
  35644. */
  35645. setOpaqueSort( method ) {
  35646. this._opaqueSort = method;
  35647. }
  35648. /**
  35649. * Defines a manual sort function for the transparent render list.
  35650. * Pass `null` to use the default sort.
  35651. *
  35652. * @param {Function} method - The sort function.
  35653. */
  35654. setTransparentSort( method ) {
  35655. this._transparentSort = method;
  35656. }
  35657. /**
  35658. * Returns the scissor rectangle.
  35659. *
  35660. * @param {Vector4} target - The method writes the result in this target object.
  35661. * @return {Vector4} The scissor rectangle.
  35662. */
  35663. getScissor( target ) {
  35664. const scissor = this._scissor;
  35665. target.x = scissor.x;
  35666. target.y = scissor.y;
  35667. target.width = scissor.width;
  35668. target.height = scissor.height;
  35669. return target;
  35670. }
  35671. /**
  35672. * Defines the scissor rectangle.
  35673. *
  35674. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  35675. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  35676. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  35677. * @param {Number} width - The width of the scissor box in logical pixel unit.
  35678. * @param {Number} height - The height of the scissor box in logical pixel unit.
  35679. */
  35680. setScissor( x, y, width, height ) {
  35681. const scissor = this._scissor;
  35682. if ( x.isVector4 ) {
  35683. scissor.copy( x );
  35684. } else {
  35685. scissor.set( x, y, width, height );
  35686. }
  35687. }
  35688. /**
  35689. * Returns the scissor test value.
  35690. *
  35691. * @return {Boolean} Whether the scissor test should be enabled or not.
  35692. */
  35693. getScissorTest() {
  35694. return this._scissorTest;
  35695. }
  35696. /**
  35697. * Defines the scissor test.
  35698. *
  35699. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  35700. */
  35701. setScissorTest( boolean ) {
  35702. this._scissorTest = boolean;
  35703. this.backend.setScissorTest( boolean );
  35704. }
  35705. /**
  35706. * Returns the viewport definition.
  35707. *
  35708. * @param {Vector4} target - The method writes the result in this target object.
  35709. * @return {Vector4} The viewport definition.
  35710. */
  35711. getViewport( target ) {
  35712. return target.copy( this._viewport );
  35713. }
  35714. /**
  35715. * Defines the viewport.
  35716. *
  35717. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35718. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35719. * @param {Number} width - The width of the viewport in logical pixel unit.
  35720. * @param {Number} height - The height of the viewport in logical pixel unit.
  35721. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  35722. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  35723. */
  35724. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  35725. const viewport = this._viewport;
  35726. if ( x.isVector4 ) {
  35727. viewport.copy( x );
  35728. } else {
  35729. viewport.set( x, y, width, height );
  35730. }
  35731. viewport.minDepth = minDepth;
  35732. viewport.maxDepth = maxDepth;
  35733. }
  35734. /**
  35735. * Returns the clear color.
  35736. *
  35737. * @param {Color} target - The method writes the result in this target object.
  35738. * @return {Color} The clear color.
  35739. */
  35740. getClearColor( target ) {
  35741. return target.copy( this._clearColor );
  35742. }
  35743. /**
  35744. * Defines the clear color and optionally the clear alpha.
  35745. *
  35746. * @param {Color} color - The clear color.
  35747. * @param {Number} [alpha=1] - The clear alpha.
  35748. */
  35749. setClearColor( color, alpha = 1 ) {
  35750. this._clearColor.set( color );
  35751. this._clearColor.a = alpha;
  35752. }
  35753. /**
  35754. * Returns the clear alpha.
  35755. *
  35756. * @return {Number} The clear alpha.
  35757. */
  35758. getClearAlpha() {
  35759. return this._clearColor.a;
  35760. }
  35761. /**
  35762. * Defines the clear alpha.
  35763. *
  35764. * @param {Number} alpha - The clear alpha.
  35765. */
  35766. setClearAlpha( alpha ) {
  35767. this._clearColor.a = alpha;
  35768. }
  35769. /**
  35770. * Returns the clear depth.
  35771. *
  35772. * @return {Number} The clear depth.
  35773. */
  35774. getClearDepth() {
  35775. return this._clearDepth;
  35776. }
  35777. /**
  35778. * Defines the clear depth.
  35779. *
  35780. * @param {Number} depth - The clear depth.
  35781. */
  35782. setClearDepth( depth ) {
  35783. this._clearDepth = depth;
  35784. }
  35785. /**
  35786. * Returns the clear stencil.
  35787. *
  35788. * @return {Number} The clear stencil.
  35789. */
  35790. getClearStencil() {
  35791. return this._clearStencil;
  35792. }
  35793. /**
  35794. * Defines the clear stencil.
  35795. *
  35796. * @param {Number} stencil - The clear stencil.
  35797. */
  35798. setClearStencil( stencil ) {
  35799. this._clearStencil = stencil;
  35800. }
  35801. /**
  35802. * This method performs an occlusion query for the given 3D object.
  35803. * It returns `true` if the given 3D object is fully occluded by other
  35804. * 3D objects in the scene.
  35805. *
  35806. * @param {Object3D} object - The 3D object to test.
  35807. * @return {Boolean} Whether the 3D object is fully occluded or not.
  35808. */
  35809. isOccluded( object ) {
  35810. const renderContext = this._currentRenderContext;
  35811. return renderContext && this.backend.isOccluded( renderContext, object );
  35812. }
  35813. /**
  35814. * Performs a manual clear operation. This method ignores `autoClear` properties.
  35815. *
  35816. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35817. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35818. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35819. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35820. * Only returned when the renderer has not been initialized.
  35821. */
  35822. clear( color = true, depth = true, stencil = true ) {
  35823. if ( this._initialized === false ) {
  35824. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  35825. return this.clearAsync( color, depth, stencil );
  35826. }
  35827. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35828. let renderContext = null;
  35829. if ( renderTarget !== null ) {
  35830. this._textures.updateRenderTarget( renderTarget );
  35831. const renderTargetData = this._textures.get( renderTarget );
  35832. renderContext = this._renderContexts.getForClear( renderTarget );
  35833. renderContext.textures = renderTargetData.textures;
  35834. renderContext.depthTexture = renderTargetData.depthTexture;
  35835. renderContext.width = renderTargetData.width;
  35836. renderContext.height = renderTargetData.height;
  35837. renderContext.renderTarget = renderTarget;
  35838. renderContext.depth = renderTarget.depthBuffer;
  35839. renderContext.stencil = renderTarget.stencilBuffer;
  35840. }
  35841. // #30329
  35842. renderContext.clearColorValue = this._clearColor;
  35843. this.backend.clear( color, depth, stencil, renderContext );
  35844. if ( renderTarget !== null && this._renderTarget === null ) {
  35845. // If a color space transform or tone mapping is required,
  35846. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  35847. const quad = this._quad;
  35848. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35849. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35850. quad.material.needsUpdate = true;
  35851. }
  35852. this._renderScene( quad, quad.camera, false );
  35853. }
  35854. }
  35855. /**
  35856. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  35857. *
  35858. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35859. * Only returned when the renderer has not been initialized.
  35860. */
  35861. clearColor() {
  35862. return this.clear( true, false, false );
  35863. }
  35864. /**
  35865. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  35866. *
  35867. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35868. * Only returned when the renderer has not been initialized.
  35869. */
  35870. clearDepth() {
  35871. return this.clear( false, true, false );
  35872. }
  35873. /**
  35874. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  35875. *
  35876. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35877. * Only returned when the renderer has not been initialized.
  35878. */
  35879. clearStencil() {
  35880. return this.clear( false, false, true );
  35881. }
  35882. /**
  35883. * Async version of {@link module:Renderer~Renderer#clear}.
  35884. *
  35885. * @async
  35886. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35887. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35888. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35889. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35890. */
  35891. async clearAsync( color = true, depth = true, stencil = true ) {
  35892. if ( this._initialized === false ) await this.init();
  35893. this.clear( color, depth, stencil );
  35894. }
  35895. /**
  35896. * Async version of {@link module:Renderer~Renderer#clearColor}.
  35897. *
  35898. * @async
  35899. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35900. */
  35901. async clearColorAsync() {
  35902. this.clearAsync( true, false, false );
  35903. }
  35904. /**
  35905. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  35906. *
  35907. * @async
  35908. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35909. */
  35910. async clearDepthAsync() {
  35911. this.clearAsync( false, true, false );
  35912. }
  35913. /**
  35914. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  35915. *
  35916. * @async
  35917. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35918. */
  35919. async clearStencilAsync() {
  35920. this.clearAsync( false, false, true );
  35921. }
  35922. /**
  35923. * The current output tone mapping of the renderer. When a render target is set,
  35924. * the output tone mapping is always `NoToneMapping`.
  35925. *
  35926. * @type {Number}
  35927. */
  35928. get currentToneMapping() {
  35929. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  35930. }
  35931. /**
  35932. * The current output color space of the renderer. When a render target is set,
  35933. * the output color space is always `LinearSRGBColorSpace`.
  35934. *
  35935. * @type {String}
  35936. */
  35937. get currentColorSpace() {
  35938. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  35939. }
  35940. /**
  35941. * Frees all internal resources of the renderer. Call this method if the renderer
  35942. * is no longer in use by your app.
  35943. */
  35944. dispose() {
  35945. this.info.dispose();
  35946. this.backend.dispose();
  35947. this._animation.dispose();
  35948. this._objects.dispose();
  35949. this._pipelines.dispose();
  35950. this._nodes.dispose();
  35951. this._bindings.dispose();
  35952. this._renderLists.dispose();
  35953. this._renderContexts.dispose();
  35954. this._textures.dispose();
  35955. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  35956. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  35957. if ( queryPool !== null ) queryPool.dispose();
  35958. } );
  35959. this.setRenderTarget( null );
  35960. this.setAnimationLoop( null );
  35961. }
  35962. /**
  35963. * Sets the given render target. Calling this method means the renderer does not
  35964. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  35965. * Use `null` as the first argument to reset the state.
  35966. *
  35967. * @param {RenderTarget?} renderTarget - The render target to set.
  35968. * @param {Number} [activeCubeFace=0] - The active cube face.
  35969. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  35970. */
  35971. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  35972. this._renderTarget = renderTarget;
  35973. this._activeCubeFace = activeCubeFace;
  35974. this._activeMipmapLevel = activeMipmapLevel;
  35975. }
  35976. /**
  35977. * Returns the current render target.
  35978. *
  35979. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  35980. */
  35981. getRenderTarget() {
  35982. return this._renderTarget;
  35983. }
  35984. /**
  35985. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  35986. *
  35987. * @callback renderObjectFunction
  35988. * @param {Object3D} object - The 3D object.
  35989. * @param {Scene} scene - The scene the 3D object belongs to.
  35990. * @param {Camera} camera - The camera the object should be rendered with.
  35991. * @param {BufferGeometry} geometry - The object's geometry.
  35992. * @param {Material} material - The object's material.
  35993. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35994. * @param {LightsNode} lightsNode - The current lights node.
  35995. * @param {ClippingContext} clippingContext - The clipping context.
  35996. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35997. */
  35998. /**
  35999. * Sets the given render object function. Calling this method overwrites the default implementation
  36000. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  36001. * if you want to modify the way objects are rendered. For example you can define things like "every
  36002. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  36003. * The custom function must always call `renderObject()` in its implementation.
  36004. *
  36005. * Use `null` as the first argument to reset the state.
  36006. *
  36007. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  36008. */
  36009. setRenderObjectFunction( renderObjectFunction ) {
  36010. this._renderObjectFunction = renderObjectFunction;
  36011. }
  36012. /**
  36013. * Returns the current render object function.
  36014. *
  36015. * @return {Function?} The current render object function. Returns `null` if no function is set.
  36016. */
  36017. getRenderObjectFunction() {
  36018. return this._renderObjectFunction;
  36019. }
  36020. /**
  36021. * Execute a single or an array of compute nodes. This method can only be called
  36022. * if the renderer has been initialized.
  36023. *
  36024. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  36025. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  36026. */
  36027. compute( computeNodes ) {
  36028. if ( this._isDeviceLost === true ) return;
  36029. if ( this._initialized === false ) {
  36030. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  36031. return this.computeAsync( computeNodes );
  36032. }
  36033. //
  36034. const nodeFrame = this._nodes.nodeFrame;
  36035. const previousRenderId = nodeFrame.renderId;
  36036. //
  36037. this.info.calls ++;
  36038. this.info.compute.calls ++;
  36039. this.info.compute.frameCalls ++;
  36040. nodeFrame.renderId = this.info.calls;
  36041. //
  36042. const backend = this.backend;
  36043. const pipelines = this._pipelines;
  36044. const bindings = this._bindings;
  36045. const nodes = this._nodes;
  36046. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36047. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36048. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36049. }
  36050. backend.beginCompute( computeNodes );
  36051. for ( const computeNode of computeList ) {
  36052. // onInit
  36053. if ( pipelines.has( computeNode ) === false ) {
  36054. const dispose = () => {
  36055. computeNode.removeEventListener( 'dispose', dispose );
  36056. pipelines.delete( computeNode );
  36057. bindings.delete( computeNode );
  36058. nodes.delete( computeNode );
  36059. };
  36060. computeNode.addEventListener( 'dispose', dispose );
  36061. //
  36062. const onInitFn = computeNode.onInitFunction;
  36063. if ( onInitFn !== null ) {
  36064. onInitFn.call( computeNode, { renderer: this } );
  36065. }
  36066. }
  36067. nodes.updateForCompute( computeNode );
  36068. bindings.updateForCompute( computeNode );
  36069. const computeBindings = bindings.getForCompute( computeNode );
  36070. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  36071. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  36072. }
  36073. backend.finishCompute( computeNodes );
  36074. //
  36075. nodeFrame.renderId = previousRenderId;
  36076. }
  36077. /**
  36078. * Execute a single or an array of compute nodes.
  36079. *
  36080. * @async
  36081. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  36082. * @return {Promise} A Promise that resolve when the compute has finished.
  36083. */
  36084. async computeAsync( computeNodes ) {
  36085. if ( this._initialized === false ) await this.init();
  36086. this.compute( computeNodes );
  36087. }
  36088. /**
  36089. * Checks if the given feature is supported by the selected backend.
  36090. *
  36091. * @async
  36092. * @param {String} name - The feature's name.
  36093. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  36094. */
  36095. async hasFeatureAsync( name ) {
  36096. if ( this._initialized === false ) await this.init();
  36097. return this.backend.hasFeature( name );
  36098. }
  36099. async resolveTimestampsAsync( type = 'render' ) {
  36100. if ( this._initialized === false ) await this.init();
  36101. return this.backend.resolveTimestampsAsync( type );
  36102. }
  36103. /**
  36104. * Checks if the given feature is supported by the selected backend. If the
  36105. * renderer has not been initialized, this method always returns `false`.
  36106. *
  36107. * @param {String} name - The feature's name.
  36108. * @return {Boolean} Whether the feature is supported or not.
  36109. */
  36110. hasFeature( name ) {
  36111. if ( this._initialized === false ) {
  36112. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  36113. return false;
  36114. }
  36115. return this.backend.hasFeature( name );
  36116. }
  36117. /**
  36118. * Returns `true` when the renderer has been initialized.
  36119. *
  36120. * @return {Boolean} Whether the renderer has been initialized or not.
  36121. */
  36122. hasInitialized() {
  36123. return this._initialized;
  36124. }
  36125. /**
  36126. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  36127. * (which can cause noticeable lags due to decode and GPU upload overhead).
  36128. *
  36129. * @async
  36130. * @param {Texture} texture - The texture.
  36131. * @return {Promise} A Promise that resolves when the texture has been initialized.
  36132. */
  36133. async initTextureAsync( texture ) {
  36134. if ( this._initialized === false ) await this.init();
  36135. this._textures.updateTexture( texture );
  36136. }
  36137. /**
  36138. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  36139. * (which can cause noticeable lags due to decode and GPU upload overhead).
  36140. *
  36141. * This method can only be used if the renderer has been initialized.
  36142. *
  36143. * @param {Texture} texture - The texture.
  36144. */
  36145. initTexture( texture ) {
  36146. if ( this._initialized === false ) {
  36147. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  36148. }
  36149. this._textures.updateTexture( texture );
  36150. }
  36151. /**
  36152. * Copies the current bound framebuffer into the given texture.
  36153. *
  36154. * @param {FramebufferTexture} framebufferTexture - The texture.
  36155. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  36156. */
  36157. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  36158. if ( rectangle !== null ) {
  36159. if ( rectangle.isVector2 ) {
  36160. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  36161. } else if ( rectangle.isVector4 ) {
  36162. rectangle = _vector4.copy( rectangle ).floor();
  36163. } else {
  36164. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  36165. return;
  36166. }
  36167. } else {
  36168. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  36169. }
  36170. //
  36171. let renderContext = this._currentRenderContext;
  36172. let renderTarget;
  36173. if ( renderContext !== null ) {
  36174. renderTarget = renderContext.renderTarget;
  36175. } else {
  36176. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36177. if ( renderTarget !== null ) {
  36178. this._textures.updateRenderTarget( renderTarget );
  36179. renderContext = this._textures.get( renderTarget );
  36180. }
  36181. }
  36182. //
  36183. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  36184. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  36185. }
  36186. /**
  36187. * Copies data of source texture into a destination texture.
  36188. *
  36189. * @param {Texture} srcTexture - The source texture.
  36190. * @param {Texture} dstTexture - The destination texture.
  36191. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  36192. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  36193. * @param {Number} level - The mipmap level to copy.
  36194. */
  36195. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  36196. this._textures.updateTexture( srcTexture );
  36197. this._textures.updateTexture( dstTexture );
  36198. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  36199. }
  36200. /**
  36201. * Reads pixel data from the given render target.
  36202. *
  36203. * @async
  36204. * @param {RenderTarget} renderTarget - The render target to read from.
  36205. * @param {Number} x - The `x` coordinate of the copy region's origin.
  36206. * @param {Number} y - The `y` coordinate of the copy region's origin.
  36207. * @param {Number} width - The width of the copy region.
  36208. * @param {Number} height - The height of the copy region.
  36209. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  36210. * @param {Number} [faceIndex=0] - The active cube face index.
  36211. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  36212. */
  36213. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  36214. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  36215. }
  36216. /**
  36217. * Analyzes the given 3D object's hierarchy and builds render lists from the
  36218. * processed hierarchy.
  36219. *
  36220. * @param {Object3D} object - The 3D object to process (usually a scene).
  36221. * @param {Camera} camera - The camera the object is rendered with.
  36222. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  36223. * @param {RenderList} renderList - The current render list.
  36224. * @param {ClippingContext} clippingContext - The current clipping context.
  36225. */
  36226. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  36227. if ( object.visible === false ) return;
  36228. const visible = object.layers.test( camera.layers );
  36229. if ( visible ) {
  36230. if ( object.isGroup ) {
  36231. groupOrder = object.renderOrder;
  36232. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  36233. } else if ( object.isLOD ) {
  36234. if ( object.autoUpdate === true ) object.update( camera );
  36235. } else if ( object.isLight ) {
  36236. renderList.pushLight( object );
  36237. } else if ( object.isSprite ) {
  36238. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  36239. if ( this.sortObjects === true ) {
  36240. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  36241. }
  36242. const { geometry, material } = object;
  36243. if ( material.visible ) {
  36244. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  36245. }
  36246. }
  36247. } else if ( object.isLineLoop ) {
  36248. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  36249. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  36250. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  36251. const { geometry, material } = object;
  36252. if ( this.sortObjects === true ) {
  36253. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  36254. _vector4
  36255. .copy( geometry.boundingSphere.center )
  36256. .applyMatrix4( object.matrixWorld )
  36257. .applyMatrix4( _projScreenMatrix );
  36258. }
  36259. if ( Array.isArray( material ) ) {
  36260. const groups = geometry.groups;
  36261. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  36262. const group = groups[ i ];
  36263. const groupMaterial = material[ group.materialIndex ];
  36264. if ( groupMaterial && groupMaterial.visible ) {
  36265. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  36266. }
  36267. }
  36268. } else if ( material.visible ) {
  36269. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  36270. }
  36271. }
  36272. }
  36273. }
  36274. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  36275. const baseRenderList = renderList;
  36276. // replace render list
  36277. renderList = this._renderLists.get( object, camera );
  36278. renderList.begin();
  36279. baseRenderList.pushBundle( {
  36280. bundleGroup: object,
  36281. camera,
  36282. renderList,
  36283. } );
  36284. renderList.finish();
  36285. }
  36286. const children = object.children;
  36287. for ( let i = 0, l = children.length; i < l; i ++ ) {
  36288. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  36289. }
  36290. }
  36291. /**
  36292. * Renders the given render bundles.
  36293. *
  36294. * @private
  36295. * @param {Array<Object>} bundles - Array with render bundle data.
  36296. * @param {Scene} sceneRef - The scene the render bundles belong to.
  36297. * @param {LightsNode} lightsNode - The current lights node.
  36298. */
  36299. _renderBundles( bundles, sceneRef, lightsNode ) {
  36300. for ( const bundle of bundles ) {
  36301. this._renderBundle( bundle, sceneRef, lightsNode );
  36302. }
  36303. }
  36304. /**
  36305. * Renders the transparent objects from the given render lists.
  36306. *
  36307. * @private
  36308. * @param {Array<Object>} renderList - The transparent render list.
  36309. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  36310. * @param {Camera} camera - The camera the render list should be rendered with.
  36311. * @param {Scene} scene - The scene the render list belongs to.
  36312. * @param {LightsNode} lightsNode - The current lights node.
  36313. */
  36314. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  36315. if ( doublePassList.length > 0 ) {
  36316. // render back side
  36317. for ( const { material } of doublePassList ) {
  36318. material.side = BackSide;
  36319. }
  36320. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  36321. // render front side
  36322. for ( const { material } of doublePassList ) {
  36323. material.side = FrontSide;
  36324. }
  36325. this._renderObjects( renderList, camera, scene, lightsNode );
  36326. // restore
  36327. for ( const { material } of doublePassList ) {
  36328. material.side = DoubleSide;
  36329. }
  36330. } else {
  36331. this._renderObjects( renderList, camera, scene, lightsNode );
  36332. }
  36333. }
  36334. /**
  36335. * Renders the objects from the given render list.
  36336. *
  36337. * @private
  36338. * @param {Array<Object>} renderList - The render list.
  36339. * @param {Camera} camera - The camera the render list should be rendered with.
  36340. * @param {Scene} scene - The scene the render list belongs to.
  36341. * @param {LightsNode} lightsNode - The current lights node.
  36342. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36343. */
  36344. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  36345. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  36346. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  36347. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  36348. }
  36349. }
  36350. /**
  36351. * This method represents the default render object function that manages the render lifecycle
  36352. * of the object.
  36353. *
  36354. * @param {Object3D} object - The 3D object.
  36355. * @param {Scene} scene - The scene the 3D object belongs to.
  36356. * @param {Camera} camera - The camera the object should be rendered with.
  36357. * @param {BufferGeometry} geometry - The object's geometry.
  36358. * @param {Material} material - The object's material.
  36359. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36360. * @param {LightsNode} lightsNode - The current lights node.
  36361. * @param {ClippingContext} clippingContext - The clipping context.
  36362. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36363. */
  36364. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  36365. let overridePositionNode;
  36366. let overrideColorNode;
  36367. let overrideDepthNode;
  36368. //
  36369. object.onBeforeRender( this, scene, camera, geometry, material, group );
  36370. //
  36371. if ( scene.overrideMaterial !== null ) {
  36372. const overrideMaterial = scene.overrideMaterial;
  36373. if ( material.positionNode && material.positionNode.isNode ) {
  36374. overridePositionNode = overrideMaterial.positionNode;
  36375. overrideMaterial.positionNode = material.positionNode;
  36376. }
  36377. overrideMaterial.alphaTest = material.alphaTest;
  36378. overrideMaterial.alphaMap = material.alphaMap;
  36379. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  36380. if ( overrideMaterial.isShadowPassMaterial ) {
  36381. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  36382. if ( material.depthNode && material.depthNode.isNode ) {
  36383. overrideDepthNode = overrideMaterial.depthNode;
  36384. overrideMaterial.depthNode = material.depthNode;
  36385. }
  36386. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  36387. overrideColorNode = overrideMaterial.colorNode;
  36388. overrideMaterial.colorNode = material.castShadowNode;
  36389. }
  36390. }
  36391. material = overrideMaterial;
  36392. }
  36393. //
  36394. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  36395. material.side = BackSide;
  36396. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  36397. material.side = FrontSide;
  36398. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  36399. material.side = DoubleSide;
  36400. } else {
  36401. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  36402. }
  36403. //
  36404. if ( overridePositionNode !== undefined ) {
  36405. scene.overrideMaterial.positionNode = overridePositionNode;
  36406. }
  36407. if ( overrideDepthNode !== undefined ) {
  36408. scene.overrideMaterial.depthNode = overrideDepthNode;
  36409. }
  36410. if ( overrideColorNode !== undefined ) {
  36411. scene.overrideMaterial.colorNode = overrideColorNode;
  36412. }
  36413. //
  36414. object.onAfterRender( this, scene, camera, geometry, material, group );
  36415. }
  36416. /**
  36417. * This method represents the default `_handleObjectFunction` implementation which creates
  36418. * a render object from the given data and performs the draw command with the selected backend.
  36419. *
  36420. * @private
  36421. * @param {Object3D} object - The 3D object.
  36422. * @param {Material} material - The object's material.
  36423. * @param {Scene} scene - The scene the 3D object belongs to.
  36424. * @param {Camera} camera - The camera the object should be rendered with.
  36425. * @param {LightsNode} lightsNode - The current lights node.
  36426. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36427. * @param {ClippingContext} clippingContext - The clipping context.
  36428. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36429. */
  36430. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36431. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36432. renderObject.drawRange = object.geometry.drawRange;
  36433. renderObject.group = group;
  36434. //
  36435. const needsRefresh = this._nodes.needsRefresh( renderObject );
  36436. if ( needsRefresh ) {
  36437. this._nodes.updateBefore( renderObject );
  36438. this._geometries.updateForRender( renderObject );
  36439. this._nodes.updateForRender( renderObject );
  36440. this._bindings.updateForRender( renderObject );
  36441. }
  36442. this._pipelines.updateForRender( renderObject );
  36443. //
  36444. if ( this._currentRenderBundle !== null ) {
  36445. const renderBundleData = this.backend.get( this._currentRenderBundle );
  36446. renderBundleData.renderObjects.push( renderObject );
  36447. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  36448. }
  36449. this.backend.draw( renderObject, this.info );
  36450. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  36451. }
  36452. /**
  36453. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  36454. * Used in `compileAsync()`.
  36455. *
  36456. * @private
  36457. * @param {Object3D} object - The 3D object.
  36458. * @param {Material} material - The object's material.
  36459. * @param {Scene} scene - The scene the 3D object belongs to.
  36460. * @param {Camera} camera - The camera the object should be rendered with.
  36461. * @param {LightsNode} lightsNode - The current lights node.
  36462. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36463. * @param {ClippingContext} clippingContext - The clipping context.
  36464. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  36465. */
  36466. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  36467. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  36468. renderObject.drawRange = object.geometry.drawRange;
  36469. renderObject.group = group;
  36470. //
  36471. this._nodes.updateBefore( renderObject );
  36472. this._geometries.updateForRender( renderObject );
  36473. this._nodes.updateForRender( renderObject );
  36474. this._bindings.updateForRender( renderObject );
  36475. this._pipelines.getForRender( renderObject, this._compilationPromises );
  36476. this._nodes.updateAfter( renderObject );
  36477. }
  36478. /**
  36479. * Alias for `compileAsync()`.
  36480. *
  36481. * @method
  36482. * @param {Object3D} scene - The scene or 3D object to precompile.
  36483. * @param {Camera} camera - The camera that is used to render the scene.
  36484. * @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.
  36485. * @return {Promise} A Promise that resolves when the compile has been finished.
  36486. */
  36487. get compile() {
  36488. return this.compileAsync;
  36489. }
  36490. }
  36491. /**
  36492. * A binding represents the connection between a resource (like a texture, sampler
  36493. * or uniform buffer) and the resource definition in a shader stage.
  36494. *
  36495. * This module is an abstract base class for all concrete bindings types.
  36496. *
  36497. * @abstract
  36498. * @private
  36499. */
  36500. class Binding {
  36501. /**
  36502. * Constructs a new binding.
  36503. *
  36504. * @param {String} [name=''] - The binding's name.
  36505. */
  36506. constructor( name = '' ) {
  36507. /**
  36508. * The binding's name.
  36509. *
  36510. * @type {String}
  36511. */
  36512. this.name = name;
  36513. /**
  36514. * A bitmask that defines in what shader stages the
  36515. * binding's resource is accessible.
  36516. *
  36517. * @type {Number}
  36518. */
  36519. this.visibility = 0;
  36520. }
  36521. /**
  36522. * Makes sure binding's resource is visible for the given shader stage.
  36523. *
  36524. * @param {Number} visibility - The shader stage.
  36525. */
  36526. setVisibility( visibility ) {
  36527. this.visibility |= visibility;
  36528. }
  36529. /**
  36530. * Clones the binding.
  36531. *
  36532. * @return {Binding} The cloned binding.
  36533. */
  36534. clone() {
  36535. return Object.assign( new this.constructor(), this );
  36536. }
  36537. }
  36538. /** @module BufferUtils **/
  36539. /**
  36540. * This function is usually called with the length in bytes of an array buffer.
  36541. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  36542. *
  36543. * @function
  36544. * @param {Number} floatLength - The buffer length.
  36545. * @return {Number} The padded length.
  36546. */
  36547. function getFloatLength( floatLength ) {
  36548. // ensure chunk size alignment (STD140 layout)
  36549. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  36550. }
  36551. /**
  36552. * Represents a buffer binding type.
  36553. *
  36554. * @private
  36555. * @abstract
  36556. * @augments Binding
  36557. */
  36558. class Buffer extends Binding {
  36559. /**
  36560. * Constructs a new buffer.
  36561. *
  36562. * @param {String} name - The buffer's name.
  36563. * @param {TypedArray} [buffer=null] - The buffer.
  36564. */
  36565. constructor( name, buffer = null ) {
  36566. super( name );
  36567. /**
  36568. * This flag can be used for type testing.
  36569. *
  36570. * @type {Boolean}
  36571. * @readonly
  36572. * @default true
  36573. */
  36574. this.isBuffer = true;
  36575. /**
  36576. * The bytes per element.
  36577. *
  36578. * @type {Number}
  36579. */
  36580. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  36581. /**
  36582. * A reference to the internal buffer.
  36583. *
  36584. * @private
  36585. * @type {TypedArray}
  36586. */
  36587. this._buffer = buffer;
  36588. }
  36589. /**
  36590. * The buffer's byte length.
  36591. *
  36592. * @type {Number}
  36593. * @readonly
  36594. */
  36595. get byteLength() {
  36596. return getFloatLength( this._buffer.byteLength );
  36597. }
  36598. /**
  36599. * A reference to the internal buffer.
  36600. *
  36601. * @type {Float32Array}
  36602. * @readonly
  36603. */
  36604. get buffer() {
  36605. return this._buffer;
  36606. }
  36607. /**
  36608. * Updates the binding.
  36609. *
  36610. * @return {Boolean} Whether the buffer has been updated and must be
  36611. * uploaded to the GPU.
  36612. */
  36613. update() {
  36614. return true;
  36615. }
  36616. }
  36617. /**
  36618. * Represents a uniform buffer binding type.
  36619. *
  36620. * @private
  36621. * @augments Buffer
  36622. */
  36623. class UniformBuffer extends Buffer {
  36624. /**
  36625. * Constructs a new uniform buffer.
  36626. *
  36627. * @param {String} name - The buffer's name.
  36628. * @param {TypedArray} [buffer=null] - The buffer.
  36629. */
  36630. constructor( name, buffer = null ) {
  36631. super( name, buffer );
  36632. /**
  36633. * This flag can be used for type testing.
  36634. *
  36635. * @type {Boolean}
  36636. * @readonly
  36637. * @default true
  36638. */
  36639. this.isUniformBuffer = true;
  36640. }
  36641. }
  36642. let _id$4 = 0;
  36643. /**
  36644. * A special form of uniform buffer binding type.
  36645. * It's buffer value is managed by a node object.
  36646. *
  36647. * @private
  36648. * @augments UniformBuffer
  36649. */
  36650. class NodeUniformBuffer extends UniformBuffer {
  36651. /**
  36652. * Constructs a new node-based uniform buffer.
  36653. *
  36654. * @param {BufferNode} nodeUniform - The uniform buffer node.
  36655. * @param {UniformGroupNode} groupNode - The uniform group node.
  36656. */
  36657. constructor( nodeUniform, groupNode ) {
  36658. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  36659. /**
  36660. * The uniform buffer node.
  36661. *
  36662. * @type {BufferNode}
  36663. */
  36664. this.nodeUniform = nodeUniform;
  36665. /**
  36666. * The uniform group node.
  36667. *
  36668. * @type {UniformGroupNode}
  36669. */
  36670. this.groupNode = groupNode;
  36671. }
  36672. /**
  36673. * The uniform buffer.
  36674. *
  36675. * @type {Float32Array}
  36676. */
  36677. get buffer() {
  36678. return this.nodeUniform.value;
  36679. }
  36680. }
  36681. /**
  36682. * This class represents a uniform buffer binding but with
  36683. * an API that allows to maintain individual uniform objects.
  36684. *
  36685. * @private
  36686. * @augments UniformBuffer
  36687. */
  36688. class UniformsGroup extends UniformBuffer {
  36689. /**
  36690. * Constructs a new uniforms group.
  36691. *
  36692. * @param {String} name - The group's name.
  36693. */
  36694. constructor( name ) {
  36695. super( name );
  36696. /**
  36697. * This flag can be used for type testing.
  36698. *
  36699. * @type {Boolean}
  36700. * @readonly
  36701. * @default true
  36702. */
  36703. this.isUniformsGroup = true;
  36704. /**
  36705. * An array with the raw uniform values.
  36706. *
  36707. * @private
  36708. * @type {Array<Number>?}
  36709. * @default null
  36710. */
  36711. this._values = null;
  36712. /**
  36713. * An array of uniform objects.
  36714. *
  36715. * The order of uniforms in this array must match the order of uniforms in the shader.
  36716. *
  36717. * @type {Array<Uniform>}
  36718. */
  36719. this.uniforms = [];
  36720. }
  36721. /**
  36722. * Adds a uniform to this group.
  36723. *
  36724. * @param {Uniform} uniform - The uniform to add.
  36725. * @return {UniformsGroup} A reference to this group.
  36726. */
  36727. addUniform( uniform ) {
  36728. this.uniforms.push( uniform );
  36729. return this;
  36730. }
  36731. /**
  36732. * Removes a uniform from this group.
  36733. *
  36734. * @param {Uniform} uniform - The uniform to remove.
  36735. * @return {UniformsGroup} A reference to this group.
  36736. */
  36737. removeUniform( uniform ) {
  36738. const index = this.uniforms.indexOf( uniform );
  36739. if ( index !== - 1 ) {
  36740. this.uniforms.splice( index, 1 );
  36741. }
  36742. return this;
  36743. }
  36744. /**
  36745. * An array with the raw uniform values.
  36746. *
  36747. * @type {Array<Number>}
  36748. */
  36749. get values() {
  36750. if ( this._values === null ) {
  36751. this._values = Array.from( this.buffer );
  36752. }
  36753. return this._values;
  36754. }
  36755. /**
  36756. * A Float32 array buffer with the uniform values.
  36757. *
  36758. * @type {Float32Array}
  36759. */
  36760. get buffer() {
  36761. let buffer = this._buffer;
  36762. if ( buffer === null ) {
  36763. const byteLength = this.byteLength;
  36764. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36765. this._buffer = buffer;
  36766. }
  36767. return buffer;
  36768. }
  36769. /**
  36770. * The byte length of the buffer with correct buffer alignment.
  36771. *
  36772. * @type {Number}
  36773. */
  36774. get byteLength() {
  36775. let offset = 0; // global buffer offset in bytes
  36776. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36777. const uniform = this.uniforms[ i ];
  36778. const { boundary, itemSize } = uniform;
  36779. // offset within a single chunk in bytes
  36780. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36781. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36782. // conformance tests
  36783. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36784. // check for chunk overflow
  36785. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36786. } else if ( chunkOffset % boundary !== 0 ) {
  36787. // check for correct alignment
  36788. offset += ( chunkOffset % boundary );
  36789. }
  36790. uniform.offset = ( offset / this.bytesPerElement );
  36791. offset += ( itemSize * this.bytesPerElement );
  36792. }
  36793. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36794. }
  36795. /**
  36796. * Updates this group by updating each uniform object of
  36797. * the internal uniform list. The uniform objects check if their
  36798. * values has actually changed so this method only returns
  36799. * `true` if there is a real value change.
  36800. *
  36801. * @return {Boolean} Whether the uniforms have been updated and
  36802. * must be uploaded to the GPU.
  36803. */
  36804. update() {
  36805. let updated = false;
  36806. for ( const uniform of this.uniforms ) {
  36807. if ( this.updateByType( uniform ) === true ) {
  36808. updated = true;
  36809. }
  36810. }
  36811. return updated;
  36812. }
  36813. /**
  36814. * Updates a given uniform by calling an update method matching
  36815. * the uniforms type.
  36816. *
  36817. * @param {Uniform} uniform - The uniform to update.
  36818. * @return {Boolean} Whether the uniform has been updated or not.
  36819. */
  36820. updateByType( uniform ) {
  36821. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36822. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36823. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36824. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36825. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36826. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36827. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36828. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36829. }
  36830. /**
  36831. * Updates a given Number uniform.
  36832. *
  36833. * @param {NumberUniform} uniform - The Number uniform.
  36834. * @return {Boolean} Whether the uniform has been updated or not.
  36835. */
  36836. updateNumber( uniform ) {
  36837. let updated = false;
  36838. const a = this.values;
  36839. const v = uniform.getValue();
  36840. const offset = uniform.offset;
  36841. const type = uniform.getType();
  36842. if ( a[ offset ] !== v ) {
  36843. const b = this._getBufferForType( type );
  36844. b[ offset ] = a[ offset ] = v;
  36845. updated = true;
  36846. }
  36847. return updated;
  36848. }
  36849. /**
  36850. * Updates a given Vector2 uniform.
  36851. *
  36852. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  36853. * @return {Boolean} Whether the uniform has been updated or not.
  36854. */
  36855. updateVector2( uniform ) {
  36856. let updated = false;
  36857. const a = this.values;
  36858. const v = uniform.getValue();
  36859. const offset = uniform.offset;
  36860. const type = uniform.getType();
  36861. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36862. const b = this._getBufferForType( type );
  36863. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36864. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36865. updated = true;
  36866. }
  36867. return updated;
  36868. }
  36869. /**
  36870. * Updates a given Vector3 uniform.
  36871. *
  36872. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  36873. * @return {Boolean} Whether the uniform has been updated or not.
  36874. */
  36875. updateVector3( uniform ) {
  36876. let updated = false;
  36877. const a = this.values;
  36878. const v = uniform.getValue();
  36879. const offset = uniform.offset;
  36880. const type = uniform.getType();
  36881. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36882. const b = this._getBufferForType( type );
  36883. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36884. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36885. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36886. updated = true;
  36887. }
  36888. return updated;
  36889. }
  36890. /**
  36891. * Updates a given Vector4 uniform.
  36892. *
  36893. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  36894. * @return {Boolean} Whether the uniform has been updated or not.
  36895. */
  36896. updateVector4( uniform ) {
  36897. let updated = false;
  36898. const a = this.values;
  36899. const v = uniform.getValue();
  36900. const offset = uniform.offset;
  36901. const type = uniform.getType();
  36902. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36903. const b = this._getBufferForType( type );
  36904. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36905. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36906. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36907. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36908. updated = true;
  36909. }
  36910. return updated;
  36911. }
  36912. /**
  36913. * Updates a given Color uniform.
  36914. *
  36915. * @param {ColorUniform} uniform - The Color uniform.
  36916. * @return {Boolean} Whether the uniform has been updated or not.
  36917. */
  36918. updateColor( uniform ) {
  36919. let updated = false;
  36920. const a = this.values;
  36921. const c = uniform.getValue();
  36922. const offset = uniform.offset;
  36923. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36924. const b = this.buffer;
  36925. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36926. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36927. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36928. updated = true;
  36929. }
  36930. return updated;
  36931. }
  36932. /**
  36933. * Updates a given Matrix3 uniform.
  36934. *
  36935. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  36936. * @return {Boolean} Whether the uniform has been updated or not.
  36937. */
  36938. updateMatrix3( uniform ) {
  36939. let updated = false;
  36940. const a = this.values;
  36941. const e = uniform.getValue().elements;
  36942. const offset = uniform.offset;
  36943. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36944. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36945. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36946. const b = this.buffer;
  36947. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36948. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36949. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36950. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36951. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36952. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36953. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36954. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36955. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36956. updated = true;
  36957. }
  36958. return updated;
  36959. }
  36960. /**
  36961. * Updates a given Matrix4 uniform.
  36962. *
  36963. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  36964. * @return {Boolean} Whether the uniform has been updated or not.
  36965. */
  36966. updateMatrix4( uniform ) {
  36967. let updated = false;
  36968. const a = this.values;
  36969. const e = uniform.getValue().elements;
  36970. const offset = uniform.offset;
  36971. if ( arraysEqual( a, e, offset ) === false ) {
  36972. const b = this.buffer;
  36973. b.set( e, offset );
  36974. setArray( a, e, offset );
  36975. updated = true;
  36976. }
  36977. return updated;
  36978. }
  36979. /**
  36980. * Returns a typed array that matches the given data type.
  36981. *
  36982. * @param {String} type - The data type.
  36983. * @return {TypedArray} The typed array.
  36984. */
  36985. _getBufferForType( type ) {
  36986. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  36987. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  36988. return this.buffer;
  36989. }
  36990. }
  36991. /**
  36992. * Sets the values of the second array to the first array.
  36993. *
  36994. * @private
  36995. * @param {TypedArray} a - The first array.
  36996. * @param {TypedArray} b - The second array.
  36997. * @param {Number} offset - An index offset for the first array.
  36998. */
  36999. function setArray( a, b, offset ) {
  37000. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37001. a[ offset + i ] = b[ i ];
  37002. }
  37003. }
  37004. /**
  37005. * Returns `true` if the given arrays are equal.
  37006. *
  37007. * @private
  37008. * @param {TypedArray} a - The first array.
  37009. * @param {TypedArray} b - The second array.
  37010. * @param {Number} offset - An index offset for the first array.
  37011. * @return {Boolean} Whether the given arrays are equal or not.
  37012. */
  37013. function arraysEqual( a, b, offset ) {
  37014. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37015. if ( a[ offset + i ] !== b[ i ] ) return false;
  37016. }
  37017. return true;
  37018. }
  37019. let _id$3 = 0;
  37020. /**
  37021. * A special form of uniforms group that represents
  37022. * the individual uniforms as node-based uniforms.
  37023. *
  37024. * @private
  37025. * @augments UniformsGroup
  37026. */
  37027. class NodeUniformsGroup extends UniformsGroup {
  37028. /**
  37029. * Constructs a new node-based uniforms group.
  37030. *
  37031. * @param {String} name - The group's name.
  37032. * @param {UniformGroupNode} groupNode - The uniform group node.
  37033. */
  37034. constructor( name, groupNode ) {
  37035. super( name );
  37036. /**
  37037. * The group's ID.
  37038. *
  37039. * @type {Number}
  37040. */
  37041. this.id = _id$3 ++;
  37042. /**
  37043. * The uniform group node.
  37044. *
  37045. * @type {UniformGroupNode}
  37046. */
  37047. this.groupNode = groupNode;
  37048. /**
  37049. * This flag can be used for type testing.
  37050. *
  37051. * @type {Boolean}
  37052. * @readonly
  37053. * @default true
  37054. */
  37055. this.isNodeUniformsGroup = true;
  37056. }
  37057. }
  37058. let _id$2 = 0;
  37059. /**
  37060. * Represents a sampled texture binding type.
  37061. *
  37062. * @private
  37063. * @augments Binding
  37064. */
  37065. class SampledTexture extends Binding {
  37066. /**
  37067. * Constructs a new sampled texture.
  37068. *
  37069. * @param {String} name - The sampled texture's name.
  37070. * @param {Texture?} texture - The texture this binding is referring to.
  37071. */
  37072. constructor( name, texture ) {
  37073. super( name );
  37074. /**
  37075. * This identifier.
  37076. *
  37077. * @type {Number}
  37078. */
  37079. this.id = _id$2 ++;
  37080. /**
  37081. * The texture this binding is referring to.
  37082. *
  37083. * @type {Texture?}
  37084. */
  37085. this.texture = texture;
  37086. /**
  37087. * The binding's version.
  37088. *
  37089. * @type {Number}
  37090. */
  37091. this.version = texture ? texture.version : 0;
  37092. /**
  37093. * Whether the texture is a storage texture or not.
  37094. *
  37095. * @type {Boolean}
  37096. * @default false
  37097. */
  37098. this.store = false;
  37099. /**
  37100. * The binding's generation which is an additional version
  37101. * qualifier.
  37102. *
  37103. * @type {Number?}
  37104. * @default null
  37105. */
  37106. this.generation = null;
  37107. /**
  37108. * This flag can be used for type testing.
  37109. *
  37110. * @type {Boolean}
  37111. * @readonly
  37112. * @default true
  37113. */
  37114. this.isSampledTexture = true;
  37115. }
  37116. /**
  37117. * Returns `true` whether this binding requires an update for the
  37118. * given generation.
  37119. *
  37120. * @param {Number} generation - The generation.
  37121. * @return {Boolean} Whether an update is required or not.
  37122. */
  37123. needsBindingsUpdate( generation ) {
  37124. const { texture } = this;
  37125. if ( generation !== this.generation ) {
  37126. this.generation = generation;
  37127. return true;
  37128. }
  37129. return texture.isVideoTexture;
  37130. }
  37131. /**
  37132. * Updates the binding.
  37133. *
  37134. * @return {Boolean} Whether the texture has been updated and must be
  37135. * uploaded to the GPU.
  37136. */
  37137. update() {
  37138. const { texture, version } = this;
  37139. if ( version !== texture.version ) {
  37140. this.version = texture.version;
  37141. return true;
  37142. }
  37143. return false;
  37144. }
  37145. }
  37146. /**
  37147. * A special form of sampled texture binding type.
  37148. * It's texture value is managed by a node object.
  37149. *
  37150. * @private
  37151. * @augments SampledTexture
  37152. */
  37153. class NodeSampledTexture extends SampledTexture {
  37154. /**
  37155. * Constructs a new node-based sampled texture.
  37156. *
  37157. * @param {String} name - The textures's name.
  37158. * @param {TextureNode} textureNode - The texture node.
  37159. * @param {UniformGroupNode} groupNode - The uniform group node.
  37160. * @param {String?} [access=null] - The access type.
  37161. */
  37162. constructor( name, textureNode, groupNode, access = null ) {
  37163. super( name, textureNode ? textureNode.value : null );
  37164. /**
  37165. * The texture node.
  37166. *
  37167. * @type {TextureNode}
  37168. */
  37169. this.textureNode = textureNode;
  37170. /**
  37171. * The uniform group node.
  37172. *
  37173. * @type {UniformGroupNode}
  37174. */
  37175. this.groupNode = groupNode;
  37176. /**
  37177. * The access type.
  37178. *
  37179. * @type {String?}
  37180. * @default null
  37181. */
  37182. this.access = access;
  37183. }
  37184. /**
  37185. * Overwrites the default to additionally check if the node value has changed.
  37186. *
  37187. * @param {Number} generation - The generation.
  37188. * @return {Boolean} Whether an update is required or not.
  37189. */
  37190. needsBindingsUpdate( generation ) {
  37191. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  37192. }
  37193. /**
  37194. * Updates the binding.
  37195. *
  37196. * @return {Boolean} Whether the texture has been updated and must be
  37197. * uploaded to the GPU.
  37198. */
  37199. update() {
  37200. const { textureNode } = this;
  37201. if ( this.texture !== textureNode.value ) {
  37202. this.texture = textureNode.value;
  37203. return true;
  37204. }
  37205. return super.update();
  37206. }
  37207. }
  37208. /**
  37209. * A special form of sampled cube texture binding type.
  37210. * It's texture value is managed by a node object.
  37211. *
  37212. * @private
  37213. * @augments NodeSampledTexture
  37214. */
  37215. class NodeSampledCubeTexture extends NodeSampledTexture {
  37216. /**
  37217. * Constructs a new node-based sampled cube texture.
  37218. *
  37219. * @param {String} name - The textures's name.
  37220. * @param {TextureNode} textureNode - The texture node.
  37221. * @param {UniformGroupNode} groupNode - The uniform group node.
  37222. * @param {String?} [access=null] - The access type.
  37223. */
  37224. constructor( name, textureNode, groupNode, access = null ) {
  37225. super( name, textureNode, groupNode, access );
  37226. /**
  37227. * This flag can be used for type testing.
  37228. *
  37229. * @type {Boolean}
  37230. * @readonly
  37231. * @default true
  37232. */
  37233. this.isSampledCubeTexture = true;
  37234. }
  37235. }
  37236. /**
  37237. * A special form of sampled 3D texture binding type.
  37238. * It's texture value is managed by a node object.
  37239. *
  37240. * @private
  37241. * @augments NodeSampledTexture
  37242. */
  37243. class NodeSampledTexture3D extends NodeSampledTexture {
  37244. /**
  37245. * Constructs a new node-based sampled 3D texture.
  37246. *
  37247. * @param {String} name - The textures's name.
  37248. * @param {TextureNode} textureNode - The texture node.
  37249. * @param {UniformGroupNode} groupNode - The uniform group node.
  37250. * @param {String?} [access=null] - The access type.
  37251. */
  37252. constructor( name, textureNode, groupNode, access = null ) {
  37253. super( name, textureNode, groupNode, access );
  37254. /**
  37255. * This flag can be used for type testing.
  37256. *
  37257. * @type {Boolean}
  37258. * @readonly
  37259. * @default true
  37260. */
  37261. this.isSampledTexture3D = true;
  37262. }
  37263. }
  37264. const glslMethods = {
  37265. textureDimensions: 'textureSize',
  37266. equals: 'equal'
  37267. };
  37268. const precisionLib = {
  37269. low: 'lowp',
  37270. medium: 'mediump',
  37271. high: 'highp'
  37272. };
  37273. const supports$1 = {
  37274. swizzleAssign: true,
  37275. storageBuffer: false
  37276. };
  37277. const defaultPrecisions = `
  37278. precision highp float;
  37279. precision highp int;
  37280. precision highp sampler2D;
  37281. precision highp sampler3D;
  37282. precision highp samplerCube;
  37283. precision highp sampler2DArray;
  37284. precision highp usampler2D;
  37285. precision highp usampler3D;
  37286. precision highp usamplerCube;
  37287. precision highp usampler2DArray;
  37288. precision highp isampler2D;
  37289. precision highp isampler3D;
  37290. precision highp isamplerCube;
  37291. precision highp isampler2DArray;
  37292. precision lowp sampler2DShadow;
  37293. `;
  37294. /**
  37295. * A node builder targeting GLSL.
  37296. *
  37297. * This module generates GLSL shader code from node materials and also
  37298. * generates the respective bindings and vertex buffer definitions. These
  37299. * data are later used by the renderer to create render and compute pipelines
  37300. * for render objects.
  37301. *
  37302. * @augments NodeBuilder
  37303. */
  37304. class GLSLNodeBuilder extends NodeBuilder {
  37305. /**
  37306. * Constructs a new GLSL node builder renderer.
  37307. *
  37308. * @param {Object3D} object - The 3D object.
  37309. * @param {Renderer} renderer - The renderer.
  37310. */
  37311. constructor( object, renderer ) {
  37312. super( object, renderer, new GLSLNodeParser() );
  37313. /**
  37314. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  37315. * another dictionary which manages UBOs per group ('render','frame','object').
  37316. *
  37317. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  37318. */
  37319. this.uniformGroups = {};
  37320. /**
  37321. * An array that holds objects defining the varying and attribute data in
  37322. * context of Transform Feedback.
  37323. *
  37324. * @type {Object<String,Map<String,Object>>}
  37325. */
  37326. this.transforms = [];
  37327. /**
  37328. * A dictionary that holds for each shader stage a Map of used extensions.
  37329. *
  37330. * @type {Object<String,Map<String,Object>>}
  37331. */
  37332. this.extensions = {};
  37333. /**
  37334. * A dictionary that holds for each shader stage an Array of used builtins.
  37335. *
  37336. * @type {Object<String,Array<String>>}
  37337. */
  37338. this.builtins = { vertex: [], fragment: [], compute: [] };
  37339. /**
  37340. * Whether comparison in shader code are generated with methods or not.
  37341. *
  37342. * @type {Boolean}
  37343. * @default true
  37344. */
  37345. this.useComparisonMethod = true;
  37346. }
  37347. /**
  37348. * Checks if the given texture requires a manual conversion to the working color space.
  37349. *
  37350. * @param {Texture} texture - The texture to check.
  37351. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  37352. */
  37353. needsToWorkingColorSpace( texture ) {
  37354. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  37355. }
  37356. /**
  37357. * Returns the native shader method name for a given generic name.
  37358. *
  37359. * @param {String} method - The method name to resolve.
  37360. * @return {String} The resolved GLSL method name.
  37361. */
  37362. getMethod( method ) {
  37363. return glslMethods[ method ] || method;
  37364. }
  37365. /**
  37366. * Returns the output struct name. Not relevant for GLSL.
  37367. *
  37368. * @return {String}
  37369. */
  37370. getOutputStructName() {
  37371. return '';
  37372. }
  37373. /**
  37374. * Builds the given shader node.
  37375. *
  37376. * @param {ShaderNodeInternal} shaderNode - The shader node.
  37377. * @return {String} The GLSL function code.
  37378. */
  37379. buildFunctionCode( shaderNode ) {
  37380. const layout = shaderNode.layout;
  37381. const flowData = this.flowShaderNode( shaderNode );
  37382. const parameters = [];
  37383. for ( const input of layout.inputs ) {
  37384. parameters.push( this.getType( input.type ) + ' ' + input.name );
  37385. }
  37386. //
  37387. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  37388. ${ flowData.vars }
  37389. ${ flowData.code }
  37390. return ${ flowData.result };
  37391. }`;
  37392. //
  37393. return code;
  37394. }
  37395. /**
  37396. * Setups the Pixel Buffer Object (PBO) for the given storage
  37397. * buffer node.
  37398. *
  37399. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  37400. */
  37401. setupPBO( storageBufferNode ) {
  37402. const attribute = storageBufferNode.value;
  37403. if ( attribute.pbo === undefined ) {
  37404. const originalArray = attribute.array;
  37405. const numElements = attribute.count * attribute.itemSize;
  37406. const { itemSize } = attribute;
  37407. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  37408. let format = isInteger ? RedIntegerFormat : RedFormat;
  37409. if ( itemSize === 2 ) {
  37410. format = isInteger ? RGIntegerFormat : RGFormat;
  37411. } else if ( itemSize === 3 ) {
  37412. format = isInteger ? RGBIntegerFormat : RGBFormat;
  37413. } else if ( itemSize === 4 ) {
  37414. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  37415. }
  37416. const typeMap = {
  37417. Float32Array: FloatType,
  37418. Uint8Array: UnsignedByteType,
  37419. Uint16Array: UnsignedShortType,
  37420. Uint32Array: UnsignedIntType,
  37421. Int8Array: ByteType,
  37422. Int16Array: ShortType,
  37423. Int32Array: IntType,
  37424. Uint8ClampedArray: UnsignedByteType,
  37425. };
  37426. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  37427. let height = Math.ceil( ( numElements / itemSize ) / width );
  37428. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  37429. const newSize = width * height * itemSize;
  37430. const newArray = new originalArray.constructor( newSize );
  37431. newArray.set( originalArray, 0 );
  37432. attribute.array = newArray;
  37433. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  37434. pboTexture.needsUpdate = true;
  37435. pboTexture.isPBOTexture = true;
  37436. const pbo = new TextureNode( pboTexture, null, null );
  37437. pbo.setPrecision( 'high' );
  37438. attribute.pboNode = pbo;
  37439. attribute.pbo = pbo.value;
  37440. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37441. }
  37442. }
  37443. /**
  37444. * Returns a GLSL snippet that represents the property name of the given node.
  37445. *
  37446. * @param {Node} node - The node.
  37447. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37448. * @return {String} The property name.
  37449. */
  37450. getPropertyName( node, shaderStage = this.shaderStage ) {
  37451. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  37452. return shaderStage.charAt( 0 ) + '_' + node.name;
  37453. }
  37454. return super.getPropertyName( node, shaderStage );
  37455. }
  37456. /**
  37457. * Setups the Pixel Buffer Object (PBO) for the given storage
  37458. * buffer node.
  37459. *
  37460. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  37461. * @return {String} The property name.
  37462. */
  37463. generatePBO( storageArrayElementNode ) {
  37464. const { node, indexNode } = storageArrayElementNode;
  37465. const attribute = node.value;
  37466. if ( this.renderer.backend.has( attribute ) ) {
  37467. const attributeData = this.renderer.backend.get( attribute );
  37468. attributeData.pbo = attribute.pbo;
  37469. }
  37470. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  37471. const textureName = this.getPropertyName( nodeUniform );
  37472. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  37473. const indexSnippet = indexNode.build( this, 'uint' );
  37474. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  37475. let propertyName = elementNodeData.propertyName;
  37476. if ( propertyName === undefined ) {
  37477. // property element
  37478. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  37479. propertyName = this.getPropertyName( nodeVar );
  37480. // property size
  37481. const bufferNodeData = this.getDataFromNode( node );
  37482. let propertySizeName = bufferNodeData.propertySizeName;
  37483. if ( propertySizeName === undefined ) {
  37484. propertySizeName = propertyName + 'Size';
  37485. this.getVarFromNode( node, propertySizeName, 'uint' );
  37486. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  37487. bufferNodeData.propertySizeName = propertySizeName;
  37488. }
  37489. //
  37490. const { itemSize } = attribute;
  37491. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  37492. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  37493. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  37494. //
  37495. let prefix = 'vec4';
  37496. if ( attribute.pbo.type === UnsignedIntType ) {
  37497. prefix = 'uvec4';
  37498. } else if ( attribute.pbo.type === IntType ) {
  37499. prefix = 'ivec4';
  37500. }
  37501. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  37502. elementNodeData.propertyName = propertyName;
  37503. }
  37504. return propertyName;
  37505. }
  37506. /**
  37507. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  37508. *
  37509. * @param {Texture} texture - The texture.
  37510. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37511. * @param {String} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37512. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37513. * @param {String} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37514. * @return {String} The GLSL snippet.
  37515. */
  37516. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  37517. if ( depthSnippet ) {
  37518. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  37519. } else {
  37520. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  37521. }
  37522. }
  37523. /**
  37524. * Generates the GLSL snippet for sampling/loading the given texture.
  37525. *
  37526. * @param {Texture} texture - The texture.
  37527. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37528. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37529. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  37530. * @return {String} The GLSL snippet.
  37531. */
  37532. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  37533. if ( texture.isDepthTexture ) {
  37534. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  37535. } else {
  37536. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  37537. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  37538. }
  37539. }
  37540. /**
  37541. * Generates the GLSL snippet when sampling textures with explicit mip level.
  37542. *
  37543. * @param {Texture} texture - The texture.
  37544. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37545. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37546. * @param {String} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  37547. * @return {String} The GLSL snippet.
  37548. */
  37549. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  37550. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  37551. }
  37552. /**
  37553. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  37554. *
  37555. * @param {Texture} texture - The texture.
  37556. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37557. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37558. * @param {String} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  37559. * @return {String} The GLSL snippet.
  37560. */
  37561. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  37562. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  37563. }
  37564. /**
  37565. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  37566. *
  37567. * @param {Texture} texture - The texture.
  37568. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37569. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37570. * @param {Array<String>} gradSnippet - An array holding both gradient GLSL snippets.
  37571. * @return {String} The GLSL snippet.
  37572. */
  37573. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  37574. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  37575. }
  37576. /**
  37577. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  37578. * against a reference value.
  37579. *
  37580. * @param {Texture} texture - The texture.
  37581. * @param {String} textureProperty - The name of the texture uniform in the shader.
  37582. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  37583. * @param {String} compareSnippet - A GLSL snippet that represents the reference value.
  37584. * @param {String?} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  37585. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  37586. * @return {String} The GLSL snippet.
  37587. */
  37588. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  37589. if ( shaderStage === 'fragment' ) {
  37590. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  37591. } else {
  37592. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  37593. }
  37594. }
  37595. /**
  37596. * Returns the variables of the given shader stage as a GLSL string.
  37597. *
  37598. * @param {String} shaderStage - The shader stage.
  37599. * @return {String} The GLSL snippet that defines the variables.
  37600. */
  37601. getVars( shaderStage ) {
  37602. const snippets = [];
  37603. const vars = this.vars[ shaderStage ];
  37604. if ( vars !== undefined ) {
  37605. for ( const variable of vars ) {
  37606. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  37607. }
  37608. }
  37609. return snippets.join( '\n\t' );
  37610. }
  37611. /**
  37612. * Returns the uniforms of the given shader stage as a GLSL string.
  37613. *
  37614. * @param {String} shaderStage - The shader stage.
  37615. * @return {String} The GLSL snippet that defines the uniforms.
  37616. */
  37617. getUniforms( shaderStage ) {
  37618. const uniforms = this.uniforms[ shaderStage ];
  37619. const bindingSnippets = [];
  37620. const uniformGroups = {};
  37621. for ( const uniform of uniforms ) {
  37622. let snippet = null;
  37623. let group = false;
  37624. if ( uniform.type === 'texture' ) {
  37625. const texture = uniform.node.value;
  37626. let typePrefix = '';
  37627. if ( texture.isDataTexture === true ) {
  37628. if ( texture.type === UnsignedIntType ) {
  37629. typePrefix = 'u';
  37630. } else if ( texture.type === IntType ) {
  37631. typePrefix = 'i';
  37632. }
  37633. }
  37634. if ( texture.compareFunction ) {
  37635. snippet = `sampler2DShadow ${ uniform.name };`;
  37636. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  37637. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  37638. } else {
  37639. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  37640. }
  37641. } else if ( uniform.type === 'cubeTexture' ) {
  37642. snippet = `samplerCube ${ uniform.name };`;
  37643. } else if ( uniform.type === 'texture3D' ) {
  37644. snippet = `sampler3D ${ uniform.name };`;
  37645. } else if ( uniform.type === 'buffer' ) {
  37646. const bufferNode = uniform.node;
  37647. const bufferType = this.getType( bufferNode.bufferType );
  37648. const bufferCount = bufferNode.bufferCount;
  37649. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  37650. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  37651. } else {
  37652. const vectorType = this.getVectorType( uniform.type );
  37653. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  37654. group = true;
  37655. }
  37656. const precision = uniform.node.precision;
  37657. if ( precision !== null ) {
  37658. snippet = precisionLib[ precision ] + ' ' + snippet;
  37659. }
  37660. if ( group ) {
  37661. snippet = '\t' + snippet;
  37662. const groupName = uniform.groupNode.name;
  37663. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  37664. groupSnippets.push( snippet );
  37665. } else {
  37666. snippet = 'uniform ' + snippet;
  37667. bindingSnippets.push( snippet );
  37668. }
  37669. }
  37670. let output = '';
  37671. for ( const name in uniformGroups ) {
  37672. const groupSnippets = uniformGroups[ name ];
  37673. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37674. }
  37675. output += bindingSnippets.join( '\n' );
  37676. return output;
  37677. }
  37678. /**
  37679. * Returns the type for a given buffer attribute.
  37680. *
  37681. * @param {BufferAttribute} attribute - The buffer attribute.
  37682. * @return {String} The type.
  37683. */
  37684. getTypeFromAttribute( attribute ) {
  37685. let nodeType = super.getTypeFromAttribute( attribute );
  37686. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37687. let dataAttribute = attribute;
  37688. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37689. const array = dataAttribute.array;
  37690. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  37691. nodeType = nodeType.slice( 1 );
  37692. }
  37693. }
  37694. return nodeType;
  37695. }
  37696. /**
  37697. * Returns the shader attributes of the given shader stage as a GLSL string.
  37698. *
  37699. * @param {String} shaderStage - The shader stage.
  37700. * @return {String} The GLSL snippet that defines the shader attributes.
  37701. */
  37702. getAttributes( shaderStage ) {
  37703. let snippet = '';
  37704. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37705. const attributes = this.getAttributesArray();
  37706. let location = 0;
  37707. for ( const attribute of attributes ) {
  37708. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37709. }
  37710. }
  37711. return snippet;
  37712. }
  37713. /**
  37714. * Returns the members of the given struct type node as a GLSL string.
  37715. *
  37716. * @param {StructTypeNode} struct - The struct type node.
  37717. * @return {String} The GLSL snippet that defines the struct members.
  37718. */
  37719. getStructMembers( struct ) {
  37720. const snippets = [];
  37721. for ( const member of struct.members ) {
  37722. snippets.push( `\t${ member.type } ${ member.name };` );
  37723. }
  37724. return snippets.join( '\n' );
  37725. }
  37726. /**
  37727. * Returns the structs of the given shader stage as a GLSL string.
  37728. *
  37729. * @param {String} shaderStage - The shader stage.
  37730. * @return {String} The GLSL snippet that defines the structs.
  37731. */
  37732. getStructs( shaderStage ) {
  37733. const snippets = [];
  37734. const structs = this.structs[ shaderStage ];
  37735. const outputSnippet = [];
  37736. for ( const struct of structs ) {
  37737. if ( struct.output ) {
  37738. for ( const member of struct.members ) {
  37739. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  37740. }
  37741. } else {
  37742. let snippet = 'struct ' + struct.name + ' {\n';
  37743. snippet += this.getStructMembers( struct );
  37744. snippet += '\n};\n';
  37745. snippets.push( snippet );
  37746. }
  37747. }
  37748. if ( outputSnippet.length === 0 ) {
  37749. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  37750. }
  37751. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  37752. }
  37753. /**
  37754. * Returns the varyings of the given shader stage as a GLSL string.
  37755. *
  37756. * @param {String} shaderStage - The shader stage.
  37757. * @return {String} The GLSL snippet that defines the varyings.
  37758. */
  37759. getVaryings( shaderStage ) {
  37760. let snippet = '';
  37761. const varyings = this.varyings;
  37762. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37763. for ( const varying of varyings ) {
  37764. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37765. const type = this.getType( varying.type );
  37766. if ( varying.needsInterpolation ) {
  37767. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37768. snippet += `${flat} out ${type} ${varying.name};\n`;
  37769. } else {
  37770. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  37771. }
  37772. }
  37773. } else if ( shaderStage === 'fragment' ) {
  37774. for ( const varying of varyings ) {
  37775. if ( varying.needsInterpolation ) {
  37776. const type = this.getType( varying.type );
  37777. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37778. snippet += `${flat}in ${type} ${varying.name};\n`;
  37779. }
  37780. }
  37781. }
  37782. for ( const builtin of this.builtins[ shaderStage ] ) {
  37783. snippet += `${builtin};\n`;
  37784. }
  37785. return snippet;
  37786. }
  37787. /**
  37788. * Returns the vertex index builtin.
  37789. *
  37790. * @return {String} The vertex index.
  37791. */
  37792. getVertexIndex() {
  37793. return 'uint( gl_VertexID )';
  37794. }
  37795. /**
  37796. * Returns the instance index builtin.
  37797. *
  37798. * @return {String} The instance index.
  37799. */
  37800. getInstanceIndex() {
  37801. return 'uint( gl_InstanceID )';
  37802. }
  37803. /**
  37804. * Returns the invocation local index builtin.
  37805. *
  37806. * @return {String} The invocation local index.
  37807. */
  37808. getInvocationLocalIndex() {
  37809. const workgroupSize = this.object.workgroupSize;
  37810. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  37811. return `uint( gl_InstanceID ) % ${size}u`;
  37812. }
  37813. /**
  37814. * Returns the draw index builtin.
  37815. *
  37816. * @return {String?} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  37817. */
  37818. getDrawIndex() {
  37819. const extensions = this.renderer.backend.extensions;
  37820. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37821. return 'uint( gl_DrawID )';
  37822. }
  37823. return null;
  37824. }
  37825. /**
  37826. * Returns the front facing builtin.
  37827. *
  37828. * @return {String} The front facing builtin.
  37829. */
  37830. getFrontFacing() {
  37831. return 'gl_FrontFacing';
  37832. }
  37833. /**
  37834. * Returns the frag coord builtin.
  37835. *
  37836. * @return {String} The frag coord builtin.
  37837. */
  37838. getFragCoord() {
  37839. return 'gl_FragCoord.xy';
  37840. }
  37841. /**
  37842. * Returns the frag depth builtin.
  37843. *
  37844. * @return {String} The frag depth builtin.
  37845. */
  37846. getFragDepth() {
  37847. return 'gl_FragDepth';
  37848. }
  37849. /**
  37850. * Enables the given extension.
  37851. *
  37852. * @param {String} name - The extension name.
  37853. * @param {String} behavior - The extension behavior.
  37854. * @param {String} [shaderStage=this.shaderStage] - The shader stage.
  37855. */
  37856. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  37857. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  37858. if ( map.has( name ) === false ) {
  37859. map.set( name, {
  37860. name,
  37861. behavior
  37862. } );
  37863. }
  37864. }
  37865. /**
  37866. * Returns the enabled extensions of the given shader stage as a GLSL string.
  37867. *
  37868. * @param {String} shaderStage - The shader stage.
  37869. * @return {String} The GLSL snippet that defines the enabled extensions.
  37870. */
  37871. getExtensions( shaderStage ) {
  37872. const snippets = [];
  37873. if ( shaderStage === 'vertex' ) {
  37874. const ext = this.renderer.backend.extensions;
  37875. const isBatchedMesh = this.object.isBatchedMesh;
  37876. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37877. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  37878. }
  37879. }
  37880. const extensions = this.extensions[ shaderStage ];
  37881. if ( extensions !== undefined ) {
  37882. for ( const { name, behavior } of extensions.values() ) {
  37883. snippets.push( `#extension ${name} : ${behavior}` );
  37884. }
  37885. }
  37886. return snippets.join( '\n' );
  37887. }
  37888. /**
  37889. * Returns the clip distances builtin.
  37890. *
  37891. * @return {String} The clip distances builtin.
  37892. */
  37893. getClipDistance() {
  37894. return 'gl_ClipDistance';
  37895. }
  37896. /**
  37897. * Whether the requested feature is available or not.
  37898. *
  37899. * @param {String} name - The requested feature.
  37900. * @return {Boolean} Whether the requested feature is supported or not.
  37901. */
  37902. isAvailable( name ) {
  37903. let result = supports$1[ name ];
  37904. if ( result === undefined ) {
  37905. let extensionName;
  37906. result = false;
  37907. switch ( name ) {
  37908. case 'float32Filterable':
  37909. extensionName = 'OES_texture_float_linear';
  37910. break;
  37911. case 'clipDistance':
  37912. extensionName = 'WEBGL_clip_cull_distance';
  37913. break;
  37914. }
  37915. if ( extensionName !== undefined ) {
  37916. const extensions = this.renderer.backend.extensions;
  37917. if ( extensions.has( extensionName ) ) {
  37918. extensions.get( extensionName );
  37919. result = true;
  37920. }
  37921. }
  37922. supports$1[ name ] = result;
  37923. }
  37924. return result;
  37925. }
  37926. /**
  37927. * Whether to flip texture data along its vertical axis or not.
  37928. *
  37929. * @return {Boolean} Returns always `true` in context of GLSL.
  37930. */
  37931. isFlipY() {
  37932. return true;
  37933. }
  37934. /**
  37935. * Enables hardware clipping.
  37936. *
  37937. * @param {String} planeCount - The clipping plane count.
  37938. */
  37939. enableHardwareClipping( planeCount ) {
  37940. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  37941. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  37942. }
  37943. /**
  37944. * Registers a transform in context of Transform Feedback.
  37945. *
  37946. * @param {String} varyingName - The varying name.
  37947. * @param {AttributeNode} attributeNode - The attribute node.
  37948. */
  37949. registerTransform( varyingName, attributeNode ) {
  37950. this.transforms.push( { varyingName, attributeNode } );
  37951. }
  37952. /**
  37953. * Returns the transforms of the given shader stage as a GLSL string.
  37954. *
  37955. * @param {String} shaderStage - The shader stage.
  37956. * @return {String} The GLSL snippet that defines the transforms.
  37957. */
  37958. getTransforms( /* shaderStage */ ) {
  37959. const transforms = this.transforms;
  37960. let snippet = '';
  37961. for ( let i = 0; i < transforms.length; i ++ ) {
  37962. const transform = transforms[ i ];
  37963. const attributeName = this.getPropertyName( transform.attributeNode );
  37964. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37965. }
  37966. return snippet;
  37967. }
  37968. /**
  37969. * Returns a GLSL struct based on the given name and variables.
  37970. *
  37971. * @private
  37972. * @param {String} name - The struct name.
  37973. * @param {String} vars - The struct variables.
  37974. * @return {String} The GLSL snippet representing a struct.
  37975. */
  37976. _getGLSLUniformStruct( name, vars ) {
  37977. return `
  37978. layout( std140 ) uniform ${name} {
  37979. ${vars}
  37980. };`;
  37981. }
  37982. /**
  37983. * Returns a GLSL vertex shader based on the given shader data.
  37984. *
  37985. * @private
  37986. * @param {Object} shaderData - The shader data.
  37987. * @return {String} The vertex shader.
  37988. */
  37989. _getGLSLVertexCode( shaderData ) {
  37990. return `#version 300 es
  37991. ${ this.getSignature() }
  37992. // extensions
  37993. ${shaderData.extensions}
  37994. // precision
  37995. ${ defaultPrecisions }
  37996. // uniforms
  37997. ${shaderData.uniforms}
  37998. // varyings
  37999. ${shaderData.varyings}
  38000. // attributes
  38001. ${shaderData.attributes}
  38002. // codes
  38003. ${shaderData.codes}
  38004. void main() {
  38005. // vars
  38006. ${shaderData.vars}
  38007. // transforms
  38008. ${shaderData.transforms}
  38009. // flow
  38010. ${shaderData.flow}
  38011. gl_PointSize = 1.0;
  38012. }
  38013. `;
  38014. }
  38015. /**
  38016. * Returns a GLSL fragment shader based on the given shader data.
  38017. *
  38018. * @private
  38019. * @param {Object} shaderData - The shader data.
  38020. * @return {String} The vertex shader.
  38021. */
  38022. _getGLSLFragmentCode( shaderData ) {
  38023. return `#version 300 es
  38024. ${ this.getSignature() }
  38025. // precision
  38026. ${ defaultPrecisions }
  38027. // uniforms
  38028. ${shaderData.uniforms}
  38029. // varyings
  38030. ${shaderData.varyings}
  38031. // codes
  38032. ${shaderData.codes}
  38033. // structs
  38034. ${shaderData.structs}
  38035. void main() {
  38036. // vars
  38037. ${shaderData.vars}
  38038. // flow
  38039. ${shaderData.flow}
  38040. }
  38041. `;
  38042. }
  38043. /**
  38044. * Controls the code build of the shader stages.
  38045. */
  38046. buildCode() {
  38047. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  38048. this.sortBindingGroups();
  38049. for ( const shaderStage in shadersData ) {
  38050. let flow = '// code\n\n';
  38051. flow += this.flowCode[ shaderStage ];
  38052. const flowNodes = this.flowNodes[ shaderStage ];
  38053. const mainNode = flowNodes[ flowNodes.length - 1 ];
  38054. for ( const node of flowNodes ) {
  38055. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  38056. const slotName = node.name;
  38057. if ( slotName ) {
  38058. if ( flow.length > 0 ) flow += '\n';
  38059. flow += `\t// flow -> ${ slotName }\n\t`;
  38060. }
  38061. flow += `${ flowSlotData.code }\n\t`;
  38062. if ( node === mainNode && shaderStage !== 'compute' ) {
  38063. flow += '// result\n\t';
  38064. if ( shaderStage === 'vertex' ) {
  38065. flow += 'gl_Position = ';
  38066. flow += `${ flowSlotData.result };`;
  38067. } else if ( shaderStage === 'fragment' ) {
  38068. if ( ! node.outputNode.isOutputStructNode ) {
  38069. flow += 'fragColor = ';
  38070. flow += `${ flowSlotData.result };`;
  38071. }
  38072. }
  38073. }
  38074. }
  38075. const stageData = shadersData[ shaderStage ];
  38076. stageData.extensions = this.getExtensions( shaderStage );
  38077. stageData.uniforms = this.getUniforms( shaderStage );
  38078. stageData.attributes = this.getAttributes( shaderStage );
  38079. stageData.varyings = this.getVaryings( shaderStage );
  38080. stageData.vars = this.getVars( shaderStage );
  38081. stageData.structs = this.getStructs( shaderStage );
  38082. stageData.codes = this.getCodes( shaderStage );
  38083. stageData.transforms = this.getTransforms( shaderStage );
  38084. stageData.flow = flow;
  38085. }
  38086. if ( this.material !== null ) {
  38087. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  38088. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  38089. } else {
  38090. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  38091. }
  38092. }
  38093. /**
  38094. * This method is one of the more important ones since it's responsible
  38095. * for generating a matching binding instance for the given uniform node.
  38096. *
  38097. * These bindings are later used in the renderer to create bind groups
  38098. * and layouts.
  38099. *
  38100. * @param {UniformNode} node - The uniform node.
  38101. * @param {String} type - The node data type.
  38102. * @param {String} shaderStage - The shader stage.
  38103. * @param {String?} [name=null] - An optional uniform name.
  38104. * @return {NodeUniform} The node uniform object.
  38105. */
  38106. getUniformFromNode( node, type, shaderStage, name = null ) {
  38107. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  38108. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  38109. let uniformGPU = nodeData.uniformGPU;
  38110. if ( uniformGPU === undefined ) {
  38111. const group = node.groupNode;
  38112. const groupName = group.name;
  38113. const bindings = this.getBindGroupArray( groupName, shaderStage );
  38114. if ( type === 'texture' ) {
  38115. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  38116. bindings.push( uniformGPU );
  38117. } else if ( type === 'cubeTexture' ) {
  38118. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  38119. bindings.push( uniformGPU );
  38120. } else if ( type === 'texture3D' ) {
  38121. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  38122. bindings.push( uniformGPU );
  38123. } else if ( type === 'buffer' ) {
  38124. node.name = `NodeBuffer_${ node.id }`;
  38125. uniformNode.name = `buffer${ node.id }`;
  38126. const buffer = new NodeUniformBuffer( node, group );
  38127. buffer.name = node.name;
  38128. bindings.push( buffer );
  38129. uniformGPU = buffer;
  38130. } else {
  38131. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  38132. let uniformsGroup = uniformsStage[ groupName ];
  38133. if ( uniformsGroup === undefined ) {
  38134. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  38135. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  38136. uniformsStage[ groupName ] = uniformsGroup;
  38137. bindings.push( uniformsGroup );
  38138. }
  38139. uniformGPU = this.getNodeUniform( uniformNode, type );
  38140. uniformsGroup.addUniform( uniformGPU );
  38141. }
  38142. nodeData.uniformGPU = uniformGPU;
  38143. }
  38144. return uniformNode;
  38145. }
  38146. }
  38147. let _vector2 = null;
  38148. let _color4 = null;
  38149. /**
  38150. * Most of the rendering related logic is implemented in the
  38151. * {@link module:Renderer} module and related management components.
  38152. * Sometimes it is required though to execute commands which are
  38153. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  38154. * This abstract base class defines an interface that encapsulates
  38155. * all backend-related logic. Derived classes for each backend must
  38156. * implement the interface.
  38157. *
  38158. * @abstract
  38159. * @private
  38160. */
  38161. class Backend {
  38162. /**
  38163. * Constructs a new backend.
  38164. *
  38165. * @param {Object} parameters - An object holding parameters for the backend.
  38166. */
  38167. constructor( parameters = {} ) {
  38168. /**
  38169. * The parameters of the backend.
  38170. *
  38171. * @type {Object}
  38172. */
  38173. this.parameters = Object.assign( {}, parameters );
  38174. /**
  38175. * This weak map holds backend-specific data of objects
  38176. * like textures, attributes or render targets.
  38177. *
  38178. * @type {WeakMap}
  38179. */
  38180. this.data = new WeakMap();
  38181. /**
  38182. * A reference to the renderer.
  38183. *
  38184. * @type {Renderer?}
  38185. * @default null
  38186. */
  38187. this.renderer = null;
  38188. /**
  38189. * A reference to the canvas element the renderer is drawing to.
  38190. *
  38191. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  38192. * @default null
  38193. */
  38194. this.domElement = null;
  38195. /**
  38196. * A reference to the timestamp query pool.
  38197. *
  38198. * @type {{render: TimestampQueryPool?, compute: TimestampQueryPool?}}
  38199. */
  38200. this.timestampQueryPool = {
  38201. 'render': null,
  38202. 'compute': null
  38203. };
  38204. }
  38205. /**
  38206. * Initializes the backend so it is ready for usage. Concrete backends
  38207. * are supposed to implement their rendering context creation and related
  38208. * operations in this method.
  38209. *
  38210. * @async
  38211. * @param {Renderer} renderer - The renderer.
  38212. * @return {Promise} A Promise that resolves when the backend has been initialized.
  38213. */
  38214. async init( renderer ) {
  38215. this.renderer = renderer;
  38216. }
  38217. /**
  38218. * The coordinate system of the backend.
  38219. *
  38220. * @abstract
  38221. * @type {Number}
  38222. * @readonly
  38223. */
  38224. get coordinateSystem() {}
  38225. // render context
  38226. /**
  38227. * This method is executed at the beginning of a render call and
  38228. * can be used by the backend to prepare the state for upcoming
  38229. * draw calls.
  38230. *
  38231. * @abstract
  38232. * @param {RenderContext} renderContext - The render context.
  38233. */
  38234. beginRender( /*renderContext*/ ) {}
  38235. /**
  38236. * This method is executed at the end of a render call and
  38237. * can be used by the backend to finalize work after draw
  38238. * calls.
  38239. *
  38240. * @abstract
  38241. * @param {RenderContext} renderContext - The render context.
  38242. */
  38243. finishRender( /*renderContext*/ ) {}
  38244. /**
  38245. * This method is executed at the beginning of a compute call and
  38246. * can be used by the backend to prepare the state for upcoming
  38247. * compute tasks.
  38248. *
  38249. * @abstract
  38250. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38251. */
  38252. beginCompute( /*computeGroup*/ ) {}
  38253. /**
  38254. * This method is executed at the end of a compute call and
  38255. * can be used by the backend to finalize work after compute
  38256. * tasks.
  38257. *
  38258. * @abstract
  38259. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  38260. */
  38261. finishCompute( /*computeGroup*/ ) {}
  38262. // render object
  38263. /**
  38264. * Executes a draw command for the given render object.
  38265. *
  38266. * @abstract
  38267. * @param {RenderObject} renderObject - The render object to draw.
  38268. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  38269. */
  38270. draw( /*renderObject, info*/ ) { }
  38271. // compute node
  38272. /**
  38273. * Executes a compute command for the given compute node.
  38274. *
  38275. * @abstract
  38276. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  38277. * @param {Node} computeNode - The compute node.
  38278. * @param {Array<BindGroup>} bindings - The bindings.
  38279. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38280. */
  38281. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  38282. // program
  38283. /**
  38284. * Creates a shader program from the given programmable stage.
  38285. *
  38286. * @abstract
  38287. * @param {ProgrammableStage} program - The programmable stage.
  38288. */
  38289. createProgram( /*program*/ ) { }
  38290. /**
  38291. * Destroys the shader program of the given programmable stage.
  38292. *
  38293. * @abstract
  38294. * @param {ProgrammableStage} program - The programmable stage.
  38295. */
  38296. destroyProgram( /*program*/ ) { }
  38297. // bindings
  38298. /**
  38299. * Creates bindings from the given bind group definition.
  38300. *
  38301. * @abstract
  38302. * @param {BindGroup} bindGroup - The bind group.
  38303. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38304. * @param {Number} cacheIndex - The cache index.
  38305. * @param {Number} version - The version.
  38306. */
  38307. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38308. /**
  38309. * Updates the given bind group definition.
  38310. *
  38311. * @abstract
  38312. * @param {BindGroup} bindGroup - The bind group.
  38313. * @param {Array<BindGroup>} bindings - Array of bind groups.
  38314. * @param {Number} cacheIndex - The cache index.
  38315. * @param {Number} version - The version.
  38316. */
  38317. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  38318. /**
  38319. * Updates a buffer binding.
  38320. *
  38321. * @abstract
  38322. * @param {Buffer} binding - The buffer binding to update.
  38323. */
  38324. updateBinding( /*binding*/ ) { }
  38325. // pipeline
  38326. /**
  38327. * Creates a render pipeline for the given render object.
  38328. *
  38329. * @abstract
  38330. * @param {RenderObject} renderObject - The render object.
  38331. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  38332. */
  38333. createRenderPipeline( /*renderObject, promises*/ ) { }
  38334. /**
  38335. * Creates a compute pipeline for the given compute node.
  38336. *
  38337. * @abstract
  38338. * @param {ComputePipeline} computePipeline - The compute pipeline.
  38339. * @param {Array<BindGroup>} bindings - The bindings.
  38340. */
  38341. createComputePipeline( /*computePipeline, bindings*/ ) { }
  38342. // cache key
  38343. /**
  38344. * Returns `true` if the render pipeline requires an update.
  38345. *
  38346. * @abstract
  38347. * @param {RenderObject} renderObject - The render object.
  38348. * @return {Boolean} Whether the render pipeline requires an update or not.
  38349. */
  38350. needsRenderUpdate( /*renderObject*/ ) { }
  38351. /**
  38352. * Returns a cache key that is used to identify render pipelines.
  38353. *
  38354. * @abstract
  38355. * @param {RenderObject} renderObject - The render object.
  38356. * @return {String} The cache key.
  38357. */
  38358. getRenderCacheKey( /*renderObject*/ ) { }
  38359. // node builder
  38360. /**
  38361. * Returns a node builder for the given render object.
  38362. *
  38363. * @abstract
  38364. * @param {RenderObject} renderObject - The render object.
  38365. * @param {Renderer} renderer - The renderer.
  38366. * @return {NodeBuilder} The node builder.
  38367. */
  38368. createNodeBuilder( /*renderObject, renderer*/ ) { }
  38369. // textures
  38370. /**
  38371. * Creates a GPU sampler for the given texture.
  38372. *
  38373. * @abstract
  38374. * @param {Texture} texture - The texture to create the sampler for.
  38375. */
  38376. createSampler( /*texture*/ ) { }
  38377. /**
  38378. * Destroys the GPU sampler for the given texture.
  38379. *
  38380. * @abstract
  38381. * @param {Texture} texture - The texture to destroy the sampler for.
  38382. */
  38383. destroySampler( /*texture*/ ) {}
  38384. /**
  38385. * Creates a default texture for the given texture that can be used
  38386. * as a placeholder until the actual texture is ready for usage.
  38387. *
  38388. * @abstract
  38389. * @param {Texture} texture - The texture to create a default texture for.
  38390. */
  38391. createDefaultTexture( /*texture*/ ) { }
  38392. /**
  38393. * Defines a texture on the GPU for the given texture object.
  38394. *
  38395. * @abstract
  38396. * @param {Texture} texture - The texture.
  38397. * @param {Object} [options={}] - Optional configuration parameter.
  38398. */
  38399. createTexture( /*texture, options={}*/ ) { }
  38400. /**
  38401. * Uploads the updated texture data to the GPU.
  38402. *
  38403. * @abstract
  38404. * @param {Texture} texture - The texture.
  38405. * @param {Object} [options={}] - Optional configuration parameter.
  38406. */
  38407. updateTexture( /*texture, options = {}*/ ) { }
  38408. /**
  38409. * Generates mipmaps for the given texture.
  38410. *
  38411. * @abstract
  38412. * @param {Texture} texture - The texture.
  38413. */
  38414. generateMipmaps( /*texture*/ ) { }
  38415. /**
  38416. * Destroys the GPU data for the given texture object.
  38417. *
  38418. * @abstract
  38419. * @param {Texture} texture - The texture.
  38420. */
  38421. destroyTexture( /*texture*/ ) { }
  38422. /**
  38423. * Returns texture data as a typed array.
  38424. *
  38425. * @abstract
  38426. * @async
  38427. * @param {Texture} texture - The texture to copy.
  38428. * @param {Number} x - The x coordinate of the copy origin.
  38429. * @param {Number} y - The y coordinate of the copy origin.
  38430. * @param {Number} width - The width of the copy.
  38431. * @param {Number} height - The height of the copy.
  38432. * @param {Number} faceIndex - The face index.
  38433. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  38434. */
  38435. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  38436. /**
  38437. * Copies data of the given source texture to the given destination texture.
  38438. *
  38439. * @abstract
  38440. * @param {Texture} srcTexture - The source texture.
  38441. * @param {Texture} dstTexture - The destination texture.
  38442. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  38443. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  38444. * @param {Number} [level=0] - The mip level to copy.
  38445. */
  38446. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  38447. /**
  38448. * Copies the current bound framebuffer to the given texture.
  38449. *
  38450. * @abstract
  38451. * @param {Texture} texture - The destination texture.
  38452. * @param {RenderContext} renderContext - The render context.
  38453. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  38454. */
  38455. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  38456. // attributes
  38457. /**
  38458. * Creates the GPU buffer of a shader attribute.
  38459. *
  38460. * @abstract
  38461. * @param {BufferAttribute} attribute - The buffer attribute.
  38462. */
  38463. createAttribute( /*attribute*/ ) { }
  38464. /**
  38465. * Creates the GPU buffer of an indexed shader attribute.
  38466. *
  38467. * @abstract
  38468. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  38469. */
  38470. createIndexAttribute( /*attribute*/ ) { }
  38471. /**
  38472. * Creates the GPU buffer of a storage attribute.
  38473. *
  38474. * @abstract
  38475. * @param {BufferAttribute} attribute - The buffer attribute.
  38476. */
  38477. createStorageAttribute( /*attribute*/ ) { }
  38478. /**
  38479. * Updates the GPU buffer of a shader attribute.
  38480. *
  38481. * @abstract
  38482. * @param {BufferAttribute} attribute - The buffer attribute to update.
  38483. */
  38484. updateAttribute( /*attribute*/ ) { }
  38485. /**
  38486. * Destroys the GPU buffer of a shader attribute.
  38487. *
  38488. * @abstract
  38489. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  38490. */
  38491. destroyAttribute( /*attribute*/ ) { }
  38492. // canvas
  38493. /**
  38494. * Returns the backend's rendering context.
  38495. *
  38496. * @abstract
  38497. * @return {Object} The rendering context.
  38498. */
  38499. getContext() { }
  38500. /**
  38501. * Backends can use this method if they have to run
  38502. * logic when the renderer gets resized.
  38503. *
  38504. * @abstract
  38505. */
  38506. updateSize() { }
  38507. /**
  38508. * Updates the viewport with the values from the given render context.
  38509. *
  38510. * @abstract
  38511. * @param {RenderContext} renderContext - The render context.
  38512. */
  38513. updateViewport( /*renderContext*/ ) {}
  38514. // utils
  38515. /**
  38516. * Returns `true` if the given 3D object is fully occluded by other
  38517. * 3D objects in the scene. Backends must implement this method by using
  38518. * a Occlusion Query API.
  38519. *
  38520. * @abstract
  38521. * @param {RenderContext} renderContext - The render context.
  38522. * @param {Object3D} object - The 3D object to test.
  38523. * @return {Boolean} Whether the 3D object is fully occluded or not.
  38524. */
  38525. isOccluded( /*renderContext, object*/ ) {}
  38526. /**
  38527. * Resolves the time stamp for the given render context and type.
  38528. *
  38529. * @async
  38530. * @abstract
  38531. * @param {String} [type='render'] - The type of the time stamp.
  38532. * @return {Promise<Number>} A Promise that resolves with the time stamp.
  38533. */
  38534. async resolveTimestampsAsync( type = 'render' ) {
  38535. if ( ! this.trackTimestamp ) {
  38536. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  38537. return;
  38538. }
  38539. const queryPool = this.timestampQueryPool[ type ];
  38540. if ( ! queryPool ) {
  38541. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  38542. return;
  38543. }
  38544. const duration = await queryPool.resolveQueriesAsync();
  38545. this.renderer.info[ type ].timestamp = duration;
  38546. return duration;
  38547. }
  38548. /**
  38549. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38550. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38551. *
  38552. * @async
  38553. * @abstract
  38554. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38555. */
  38556. async waitForGPU() {}
  38557. /**
  38558. * This method performs a readback operation by moving buffer data from
  38559. * a storage buffer attribute from the GPU to the CPU.
  38560. *
  38561. * @async
  38562. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38563. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38564. */
  38565. async getArrayBufferAsync( /* attribute */ ) {}
  38566. /**
  38567. * Checks if the given feature is supported by the backend.
  38568. *
  38569. * @async
  38570. * @abstract
  38571. * @param {String} name - The feature's name.
  38572. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  38573. */
  38574. async hasFeatureAsync( /*name*/ ) { }
  38575. /**
  38576. * Checks if the given feature is supported by the backend.
  38577. *
  38578. * @abstract
  38579. * @param {String} name - The feature's name.
  38580. * @return {Boolean} Whether the feature is supported or not.
  38581. */
  38582. hasFeature( /*name*/ ) {}
  38583. /**
  38584. * Returns the maximum anisotropy texture filtering value.
  38585. *
  38586. * @abstract
  38587. * @return {Number} The maximum anisotropy texture filtering value.
  38588. */
  38589. getMaxAnisotropy() {}
  38590. /**
  38591. * Returns the drawing buffer size.
  38592. *
  38593. * @return {Vector2} The drawing buffer size.
  38594. */
  38595. getDrawingBufferSize() {
  38596. _vector2 = _vector2 || new Vector2();
  38597. return this.renderer.getDrawingBufferSize( _vector2 );
  38598. }
  38599. /**
  38600. * Defines the scissor test.
  38601. *
  38602. * @abstract
  38603. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  38604. */
  38605. setScissorTest( /*boolean*/ ) { }
  38606. /**
  38607. * Returns the clear color and alpha into a single
  38608. * color object.
  38609. *
  38610. * @return {Color4} The clear color.
  38611. */
  38612. getClearColor() {
  38613. const renderer = this.renderer;
  38614. _color4 = _color4 || new Color4();
  38615. renderer.getClearColor( _color4 );
  38616. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  38617. return _color4;
  38618. }
  38619. /**
  38620. * Returns the DOM element. If no DOM element exists, the backend
  38621. * creates a new one.
  38622. *
  38623. * @return {HTMLCanvasElement} The DOM element.
  38624. */
  38625. getDomElement() {
  38626. let domElement = this.domElement;
  38627. if ( domElement === null ) {
  38628. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  38629. // OffscreenCanvas does not have setAttribute, see #22811
  38630. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  38631. this.domElement = domElement;
  38632. }
  38633. return domElement;
  38634. }
  38635. /**
  38636. * Sets a dictionary for the given object into the
  38637. * internal data structure.
  38638. *
  38639. * @param {Object} object - The object.
  38640. * @param {Object} value - The dictionary to set.
  38641. */
  38642. set( object, value ) {
  38643. this.data.set( object, value );
  38644. }
  38645. /**
  38646. * Returns the dictionary for the given object.
  38647. *
  38648. * @param {Object} object - The object.
  38649. * @return {Object} The object's dictionary.
  38650. */
  38651. get( object ) {
  38652. let map = this.data.get( object );
  38653. if ( map === undefined ) {
  38654. map = {};
  38655. this.data.set( object, map );
  38656. }
  38657. return map;
  38658. }
  38659. /**
  38660. * Checks if the given object has a dictionary
  38661. * with data defined.
  38662. *
  38663. * @param {Object} object - The object.
  38664. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  38665. */
  38666. has( object ) {
  38667. return this.data.has( object );
  38668. }
  38669. /**
  38670. * Deletes an object from the internal data structure.
  38671. *
  38672. * @param {Object} object - The object to delete.
  38673. */
  38674. delete( object ) {
  38675. this.data.delete( object );
  38676. }
  38677. /**
  38678. * Frees internal resources.
  38679. *
  38680. * @abstract
  38681. */
  38682. dispose() { }
  38683. }
  38684. let _id$1 = 0;
  38685. /**
  38686. * This module is internally used in context of compute shaders.
  38687. * This type of shader is not natively supported in WebGL 2 and
  38688. * thus implemented via Transform Feedback. `DualAttributeData`
  38689. * manages the related data.
  38690. *
  38691. * @private
  38692. */
  38693. class DualAttributeData {
  38694. constructor( attributeData, dualBuffer ) {
  38695. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  38696. this.type = attributeData.type;
  38697. this.bufferType = attributeData.bufferType;
  38698. this.pbo = attributeData.pbo;
  38699. this.byteLength = attributeData.byteLength;
  38700. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  38701. this.version = attributeData.version;
  38702. this.isInteger = attributeData.isInteger;
  38703. this.activeBufferIndex = 0;
  38704. this.baseId = attributeData.id;
  38705. }
  38706. get id() {
  38707. return `${ this.baseId }|${ this.activeBufferIndex }`;
  38708. }
  38709. get bufferGPU() {
  38710. return this.buffers[ this.activeBufferIndex ];
  38711. }
  38712. get transformBuffer() {
  38713. return this.buffers[ this.activeBufferIndex ^ 1 ];
  38714. }
  38715. switchBuffers() {
  38716. this.activeBufferIndex ^= 1;
  38717. }
  38718. }
  38719. /**
  38720. * A WebGL 2 backend utility module for managing shader attributes.
  38721. *
  38722. * @private
  38723. */
  38724. class WebGLAttributeUtils {
  38725. /**
  38726. * Constructs a new utility object.
  38727. *
  38728. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38729. */
  38730. constructor( backend ) {
  38731. /**
  38732. * A reference to the WebGL 2 backend.
  38733. *
  38734. * @type {WebGLBackend}
  38735. */
  38736. this.backend = backend;
  38737. }
  38738. /**
  38739. * Creates the GPU buffer for the given buffer attribute.
  38740. *
  38741. * @param {BufferAttribute} attribute - The buffer attribute.
  38742. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38743. */
  38744. createAttribute( attribute, bufferType ) {
  38745. const backend = this.backend;
  38746. const { gl } = backend;
  38747. const array = attribute.array;
  38748. const usage = attribute.usage || gl.STATIC_DRAW;
  38749. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38750. const bufferData = backend.get( bufferAttribute );
  38751. let bufferGPU = bufferData.bufferGPU;
  38752. if ( bufferGPU === undefined ) {
  38753. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  38754. bufferData.bufferGPU = bufferGPU;
  38755. bufferData.bufferType = bufferType;
  38756. bufferData.version = bufferAttribute.version;
  38757. }
  38758. //attribute.onUploadCallback();
  38759. let type;
  38760. if ( array instanceof Float32Array ) {
  38761. type = gl.FLOAT;
  38762. } else if ( array instanceof Uint16Array ) {
  38763. if ( attribute.isFloat16BufferAttribute ) {
  38764. type = gl.HALF_FLOAT;
  38765. } else {
  38766. type = gl.UNSIGNED_SHORT;
  38767. }
  38768. } else if ( array instanceof Int16Array ) {
  38769. type = gl.SHORT;
  38770. } else if ( array instanceof Uint32Array ) {
  38771. type = gl.UNSIGNED_INT;
  38772. } else if ( array instanceof Int32Array ) {
  38773. type = gl.INT;
  38774. } else if ( array instanceof Int8Array ) {
  38775. type = gl.BYTE;
  38776. } else if ( array instanceof Uint8Array ) {
  38777. type = gl.UNSIGNED_BYTE;
  38778. } else if ( array instanceof Uint8ClampedArray ) {
  38779. type = gl.UNSIGNED_BYTE;
  38780. } else {
  38781. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  38782. }
  38783. let attributeData = {
  38784. bufferGPU,
  38785. bufferType,
  38786. type,
  38787. byteLength: array.byteLength,
  38788. bytesPerElement: array.BYTES_PER_ELEMENT,
  38789. version: attribute.version,
  38790. pbo: attribute.pbo,
  38791. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  38792. id: _id$1 ++
  38793. };
  38794. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  38795. // create buffer for transform feedback use
  38796. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  38797. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  38798. }
  38799. backend.set( attribute, attributeData );
  38800. }
  38801. /**
  38802. * Updates the GPU buffer of the given buffer attribute.
  38803. *
  38804. * @param {BufferAttribute} attribute - The buffer attribute.
  38805. */
  38806. updateAttribute( attribute ) {
  38807. const backend = this.backend;
  38808. const { gl } = backend;
  38809. const array = attribute.array;
  38810. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38811. const bufferData = backend.get( bufferAttribute );
  38812. const bufferType = bufferData.bufferType;
  38813. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  38814. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  38815. if ( updateRanges.length === 0 ) {
  38816. // Not using update ranges
  38817. gl.bufferSubData( bufferType, 0, array );
  38818. } else {
  38819. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  38820. const range = updateRanges[ i ];
  38821. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  38822. array, range.start, range.count );
  38823. }
  38824. bufferAttribute.clearUpdateRanges();
  38825. }
  38826. gl.bindBuffer( bufferType, null );
  38827. bufferData.version = bufferAttribute.version;
  38828. }
  38829. /**
  38830. * Destroys the GPU buffer of the given buffer attribute.
  38831. *
  38832. * @param {BufferAttribute} attribute - The buffer attribute.
  38833. */
  38834. destroyAttribute( attribute ) {
  38835. const backend = this.backend;
  38836. const { gl } = backend;
  38837. if ( attribute.isInterleavedBufferAttribute ) {
  38838. backend.delete( attribute.data );
  38839. }
  38840. const attributeData = backend.get( attribute );
  38841. gl.deleteBuffer( attributeData.bufferGPU );
  38842. backend.delete( attribute );
  38843. }
  38844. /**
  38845. * This method performs a readback operation by moving buffer data from
  38846. * a storage buffer attribute from the GPU to the CPU.
  38847. *
  38848. * @async
  38849. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38850. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38851. */
  38852. async getArrayBufferAsync( attribute ) {
  38853. const backend = this.backend;
  38854. const { gl } = backend;
  38855. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38856. const { bufferGPU } = backend.get( bufferAttribute );
  38857. const array = attribute.array;
  38858. const byteLength = array.byteLength;
  38859. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  38860. const writeBuffer = gl.createBuffer();
  38861. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38862. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  38863. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  38864. await backend.utils._clientWaitAsync();
  38865. const dstBuffer = new attribute.array.constructor( array.length );
  38866. // Ensure the buffer is bound before reading
  38867. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38868. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  38869. gl.deleteBuffer( writeBuffer );
  38870. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  38871. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  38872. return dstBuffer.buffer;
  38873. }
  38874. /**
  38875. * Creates a WebGL buffer with the given data.
  38876. *
  38877. * @private
  38878. * @param {WebGL2RenderingContext} gl - The rendering context.
  38879. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38880. * @param {TypedArray} array - The array of the buffer attribute.
  38881. * @param {GLenum} usage - The usage.
  38882. * @return {WebGLBuffer} The WebGL buffer.
  38883. */
  38884. _createBuffer( gl, bufferType, array, usage ) {
  38885. const bufferGPU = gl.createBuffer();
  38886. gl.bindBuffer( bufferType, bufferGPU );
  38887. gl.bufferData( bufferType, array, usage );
  38888. gl.bindBuffer( bufferType, null );
  38889. return bufferGPU;
  38890. }
  38891. }
  38892. let equationToGL, factorToGL;
  38893. /**
  38894. * A WebGL 2 backend utility module for managing the WebGL state.
  38895. *
  38896. * The major goal of this module is to reduce the number of state changes
  38897. * by caching the WEbGL state with a series of variables. In this way, the
  38898. * renderer only executes state change commands when necessary which
  38899. * improves the overall performance.
  38900. *
  38901. * @private
  38902. */
  38903. class WebGLState {
  38904. /**
  38905. * Constructs a new utility object.
  38906. *
  38907. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38908. */
  38909. constructor( backend ) {
  38910. /**
  38911. * A reference to the WebGL 2 backend.
  38912. *
  38913. * @type {WebGLBackend}
  38914. */
  38915. this.backend = backend;
  38916. /**
  38917. * A reference to the rendering context.
  38918. *
  38919. * @type {WebGL2RenderingContext}
  38920. */
  38921. this.gl = this.backend.gl;
  38922. // Below properties are intended to cache
  38923. // the WebGL state and are not explicitly
  38924. // documented for convenience reasons.
  38925. this.enabled = {};
  38926. this.currentFlipSided = null;
  38927. this.currentCullFace = null;
  38928. this.currentProgram = null;
  38929. this.currentBlendingEnabled = false;
  38930. this.currentBlending = null;
  38931. this.currentBlendSrc = null;
  38932. this.currentBlendDst = null;
  38933. this.currentBlendSrcAlpha = null;
  38934. this.currentBlendDstAlpha = null;
  38935. this.currentPremultipledAlpha = null;
  38936. this.currentPolygonOffsetFactor = null;
  38937. this.currentPolygonOffsetUnits = null;
  38938. this.currentColorMask = null;
  38939. this.currentDepthFunc = null;
  38940. this.currentDepthMask = null;
  38941. this.currentStencilFunc = null;
  38942. this.currentStencilRef = null;
  38943. this.currentStencilFuncMask = null;
  38944. this.currentStencilFail = null;
  38945. this.currentStencilZFail = null;
  38946. this.currentStencilZPass = null;
  38947. this.currentStencilMask = null;
  38948. this.currentLineWidth = null;
  38949. this.currentClippingPlanes = 0;
  38950. this.currentBoundFramebuffers = {};
  38951. this.currentDrawbuffers = new WeakMap();
  38952. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  38953. this.currentTextureSlot = null;
  38954. this.currentBoundTextures = {};
  38955. this.currentBoundBufferBases = {};
  38956. this._init();
  38957. }
  38958. /**
  38959. * Inits the state of the utility.
  38960. *
  38961. * @private
  38962. */
  38963. _init() {
  38964. const gl = this.gl;
  38965. // Store only WebGL constants here.
  38966. equationToGL = {
  38967. [ AddEquation ]: gl.FUNC_ADD,
  38968. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  38969. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  38970. };
  38971. factorToGL = {
  38972. [ ZeroFactor ]: gl.ZERO,
  38973. [ OneFactor ]: gl.ONE,
  38974. [ SrcColorFactor ]: gl.SRC_COLOR,
  38975. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  38976. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  38977. [ DstColorFactor ]: gl.DST_COLOR,
  38978. [ DstAlphaFactor ]: gl.DST_ALPHA,
  38979. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  38980. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  38981. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  38982. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  38983. };
  38984. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  38985. const viewportParam = gl.getParameter( gl.VIEWPORT );
  38986. this.currentScissor = new Vector4().fromArray( scissorParam );
  38987. this.currentViewport = new Vector4().fromArray( viewportParam );
  38988. this._tempVec4 = new Vector4();
  38989. }
  38990. /**
  38991. * Enables the given WebGL capability.
  38992. *
  38993. * This method caches the capability state so
  38994. * `gl.enable()` is only called when necessary.
  38995. *
  38996. * @param {GLenum} id - The capability to enable.
  38997. */
  38998. enable( id ) {
  38999. const { enabled } = this;
  39000. if ( enabled[ id ] !== true ) {
  39001. this.gl.enable( id );
  39002. enabled[ id ] = true;
  39003. }
  39004. }
  39005. /**
  39006. * Disables the given WebGL capability.
  39007. *
  39008. * This method caches the capability state so
  39009. * `gl.disable()` is only called when necessary.
  39010. *
  39011. * @param {GLenum} id - The capability to enable.
  39012. */
  39013. disable( id ) {
  39014. const { enabled } = this;
  39015. if ( enabled[ id ] !== false ) {
  39016. this.gl.disable( id );
  39017. enabled[ id ] = false;
  39018. }
  39019. }
  39020. /**
  39021. * Specifies whether polygons are front- or back-facing
  39022. * by setting the winding orientation.
  39023. *
  39024. * This method caches the state so `gl.frontFace()` is only
  39025. * called when necessary.
  39026. *
  39027. * @param {Boolean} flipSided - Whether triangles flipped their sides or not.
  39028. */
  39029. setFlipSided( flipSided ) {
  39030. if ( this.currentFlipSided !== flipSided ) {
  39031. const { gl } = this;
  39032. if ( flipSided ) {
  39033. gl.frontFace( gl.CW );
  39034. } else {
  39035. gl.frontFace( gl.CCW );
  39036. }
  39037. this.currentFlipSided = flipSided;
  39038. }
  39039. }
  39040. /**
  39041. * Specifies whether or not front- and/or back-facing
  39042. * polygons can be culled.
  39043. *
  39044. * This method caches the state so `gl.cullFace()` is only
  39045. * called when necessary.
  39046. *
  39047. * @param {Number} cullFace - Defines which polygons are candidates for culling.
  39048. */
  39049. setCullFace( cullFace ) {
  39050. const { gl } = this;
  39051. if ( cullFace !== CullFaceNone ) {
  39052. this.enable( gl.CULL_FACE );
  39053. if ( cullFace !== this.currentCullFace ) {
  39054. if ( cullFace === CullFaceBack ) {
  39055. gl.cullFace( gl.BACK );
  39056. } else if ( cullFace === CullFaceFront ) {
  39057. gl.cullFace( gl.FRONT );
  39058. } else {
  39059. gl.cullFace( gl.FRONT_AND_BACK );
  39060. }
  39061. }
  39062. } else {
  39063. this.disable( gl.CULL_FACE );
  39064. }
  39065. this.currentCullFace = cullFace;
  39066. }
  39067. /**
  39068. * Specifies the width of line primitives.
  39069. *
  39070. * This method caches the state so `gl.lineWidth()` is only
  39071. * called when necessary.
  39072. *
  39073. * @param {Number} width - The line width.
  39074. */
  39075. setLineWidth( width ) {
  39076. const { currentLineWidth, gl } = this;
  39077. if ( width !== currentLineWidth ) {
  39078. gl.lineWidth( width );
  39079. this.currentLineWidth = width;
  39080. }
  39081. }
  39082. /**
  39083. * Defines the blending.
  39084. *
  39085. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  39086. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  39087. *
  39088. * @param {Number} blending - The blending type.
  39089. * @param {Number} blendEquation - The blending equation.
  39090. * @param {Number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  39091. * @param {Number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  39092. * @param {Number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  39093. * @param {Number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  39094. * @param {Number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  39095. * @param {Boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  39096. */
  39097. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39098. const { gl } = this;
  39099. if ( blending === NoBlending ) {
  39100. if ( this.currentBlendingEnabled === true ) {
  39101. this.disable( gl.BLEND );
  39102. this.currentBlendingEnabled = false;
  39103. }
  39104. return;
  39105. }
  39106. if ( this.currentBlendingEnabled === false ) {
  39107. this.enable( gl.BLEND );
  39108. this.currentBlendingEnabled = true;
  39109. }
  39110. if ( blending !== CustomBlending ) {
  39111. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39112. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39113. gl.blendEquation( gl.FUNC_ADD );
  39114. this.currentBlendEquation = AddEquation;
  39115. this.currentBlendEquationAlpha = AddEquation;
  39116. }
  39117. if ( premultipliedAlpha ) {
  39118. switch ( blending ) {
  39119. case NormalBlending:
  39120. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39121. break;
  39122. case AdditiveBlending:
  39123. gl.blendFunc( gl.ONE, gl.ONE );
  39124. break;
  39125. case SubtractiveBlending:
  39126. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39127. break;
  39128. case MultiplyBlending:
  39129. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39130. break;
  39131. default:
  39132. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39133. break;
  39134. }
  39135. } else {
  39136. switch ( blending ) {
  39137. case NormalBlending:
  39138. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39139. break;
  39140. case AdditiveBlending:
  39141. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39142. break;
  39143. case SubtractiveBlending:
  39144. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39145. break;
  39146. case MultiplyBlending:
  39147. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39148. break;
  39149. default:
  39150. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39151. break;
  39152. }
  39153. }
  39154. this.currentBlendSrc = null;
  39155. this.currentBlendDst = null;
  39156. this.currentBlendSrcAlpha = null;
  39157. this.currentBlendDstAlpha = null;
  39158. this.currentBlending = blending;
  39159. this.currentPremultipledAlpha = premultipliedAlpha;
  39160. }
  39161. return;
  39162. }
  39163. // custom blending
  39164. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39165. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39166. blendDstAlpha = blendDstAlpha || blendDst;
  39167. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39168. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39169. this.currentBlendEquation = blendEquation;
  39170. this.currentBlendEquationAlpha = blendEquationAlpha;
  39171. }
  39172. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39173. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39174. this.currentBlendSrc = blendSrc;
  39175. this.currentBlendDst = blendDst;
  39176. this.currentBlendSrcAlpha = blendSrcAlpha;
  39177. this.currentBlendDstAlpha = blendDstAlpha;
  39178. }
  39179. this.currentBlending = blending;
  39180. this.currentPremultipledAlpha = false;
  39181. }
  39182. /**
  39183. * Specifies whether colors can be written when rendering
  39184. * into a framebuffer or not.
  39185. *
  39186. * This method caches the state so `gl.colorMask()` is only
  39187. * called when necessary.
  39188. *
  39189. * @param {Boolean} colorMask - The color mask.
  39190. */
  39191. setColorMask( colorMask ) {
  39192. if ( this.currentColorMask !== colorMask ) {
  39193. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39194. this.currentColorMask = colorMask;
  39195. }
  39196. }
  39197. /**
  39198. * Specifies whether the depth test is enabled or not.
  39199. *
  39200. * @param {Boolean} depthTest - Whether the depth test is enabled or not.
  39201. */
  39202. setDepthTest( depthTest ) {
  39203. const { gl } = this;
  39204. if ( depthTest ) {
  39205. this.enable( gl.DEPTH_TEST );
  39206. } else {
  39207. this.disable( gl.DEPTH_TEST );
  39208. }
  39209. }
  39210. /**
  39211. * Specifies whether depth values can be written when rendering
  39212. * into a framebuffer or not.
  39213. *
  39214. * This method caches the state so `gl.depthMask()` is only
  39215. * called when necessary.
  39216. *
  39217. * @param {Boolean} depthMask - The depth mask.
  39218. */
  39219. setDepthMask( depthMask ) {
  39220. if ( this.currentDepthMask !== depthMask ) {
  39221. this.gl.depthMask( depthMask );
  39222. this.currentDepthMask = depthMask;
  39223. }
  39224. }
  39225. /**
  39226. * Specifies the depth compare function.
  39227. *
  39228. * This method caches the state so `gl.depthFunc()` is only
  39229. * called when necessary.
  39230. *
  39231. * @param {Number} depthFunc - The depth compare function.
  39232. */
  39233. setDepthFunc( depthFunc ) {
  39234. if ( this.currentDepthFunc !== depthFunc ) {
  39235. const { gl } = this;
  39236. switch ( depthFunc ) {
  39237. case NeverDepth:
  39238. gl.depthFunc( gl.NEVER );
  39239. break;
  39240. case AlwaysDepth:
  39241. gl.depthFunc( gl.ALWAYS );
  39242. break;
  39243. case LessDepth:
  39244. gl.depthFunc( gl.LESS );
  39245. break;
  39246. case LessEqualDepth:
  39247. gl.depthFunc( gl.LEQUAL );
  39248. break;
  39249. case EqualDepth:
  39250. gl.depthFunc( gl.EQUAL );
  39251. break;
  39252. case GreaterEqualDepth:
  39253. gl.depthFunc( gl.GEQUAL );
  39254. break;
  39255. case GreaterDepth:
  39256. gl.depthFunc( gl.GREATER );
  39257. break;
  39258. case NotEqualDepth:
  39259. gl.depthFunc( gl.NOTEQUAL );
  39260. break;
  39261. default:
  39262. gl.depthFunc( gl.LEQUAL );
  39263. }
  39264. this.currentDepthFunc = depthFunc;
  39265. }
  39266. }
  39267. /**
  39268. * Specifies the viewport.
  39269. *
  39270. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  39271. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  39272. * @param {Number} width - The width of the viewport.
  39273. * @param {Number} height - The height of the viewport.
  39274. *
  39275. */
  39276. scissor( x, y, width, height ) {
  39277. const scissor = this._tempVec4.set( x, y, width, height );
  39278. if ( this.currentScissor.equals( scissor ) === false ) {
  39279. const { gl } = this;
  39280. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  39281. this.currentScissor.copy( scissor );
  39282. }
  39283. }
  39284. /**
  39285. * Specifies the viewport.
  39286. *
  39287. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  39288. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  39289. * @param {Number} width - The width of the viewport.
  39290. * @param {Number} height - The height of the viewport.
  39291. *
  39292. */
  39293. viewport( x, y, width, height ) {
  39294. const viewport = this._tempVec4.set( x, y, width, height );
  39295. if ( this.currentViewport.equals( viewport ) === false ) {
  39296. const { gl } = this;
  39297. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  39298. this.currentViewport.copy( viewport );
  39299. }
  39300. }
  39301. /**
  39302. * Defines the scissor test.
  39303. *
  39304. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  39305. */
  39306. setScissorTest( boolean ) {
  39307. const gl = this.gl;
  39308. if ( boolean ) {
  39309. gl.enable( gl.SCISSOR_TEST );
  39310. } else {
  39311. gl.disable( gl.SCISSOR_TEST );
  39312. }
  39313. }
  39314. /**
  39315. * Specifies whether the stencil test is enabled or not.
  39316. *
  39317. * @param {Boolean} stencilTest - Whether the stencil test is enabled or not.
  39318. */
  39319. setStencilTest( stencilTest ) {
  39320. const { gl } = this;
  39321. if ( stencilTest ) {
  39322. this.enable( gl.STENCIL_TEST );
  39323. } else {
  39324. this.disable( gl.STENCIL_TEST );
  39325. }
  39326. }
  39327. /**
  39328. * Specifies whether stencil values can be written when rendering
  39329. * into a framebuffer or not.
  39330. *
  39331. * This method caches the state so `gl.stencilMask()` is only
  39332. * called when necessary.
  39333. *
  39334. * @param {Boolean} stencilMask - The stencil mask.
  39335. */
  39336. setStencilMask( stencilMask ) {
  39337. if ( this.currentStencilMask !== stencilMask ) {
  39338. this.gl.stencilMask( stencilMask );
  39339. this.currentStencilMask = stencilMask;
  39340. }
  39341. }
  39342. /**
  39343. * Specifies whether the stencil test functions.
  39344. *
  39345. * This method caches the state so `gl.stencilFunc()` is only
  39346. * called when necessary.
  39347. *
  39348. * @param {Number} stencilFunc - The stencil compare function.
  39349. * @param {Number} stencilRef - The reference value for the stencil test.
  39350. * @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.
  39351. */
  39352. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39353. if ( this.currentStencilFunc !== stencilFunc ||
  39354. this.currentStencilRef !== stencilRef ||
  39355. this.currentStencilFuncMask !== stencilMask ) {
  39356. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39357. this.currentStencilFunc = stencilFunc;
  39358. this.currentStencilRef = stencilRef;
  39359. this.currentStencilFuncMask = stencilMask;
  39360. }
  39361. }
  39362. /**
  39363. * Specifies whether the stencil test operation.
  39364. *
  39365. * This method caches the state so `gl.stencilOp()` is only
  39366. * called when necessary.
  39367. *
  39368. * @param {Number} stencilFail - The function to use when the stencil test fails.
  39369. * @param {Number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  39370. * @param {Number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  39371. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  39372. */
  39373. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39374. if ( this.currentStencilFail !== stencilFail ||
  39375. this.currentStencilZFail !== stencilZFail ||
  39376. this.currentStencilZPass !== stencilZPass ) {
  39377. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39378. this.currentStencilFail = stencilFail;
  39379. this.currentStencilZFail = stencilZFail;
  39380. this.currentStencilZPass = stencilZPass;
  39381. }
  39382. }
  39383. /**
  39384. * Configures the WebGL state for the given material.
  39385. *
  39386. * @param {Material} material - The material to configure the state for.
  39387. * @param {Number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  39388. * @param {Number} hardwareClippingPlanes - The number of hardware clipping planes.
  39389. */
  39390. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  39391. const { gl } = this;
  39392. material.side === DoubleSide
  39393. ? this.disable( gl.CULL_FACE )
  39394. : this.enable( gl.CULL_FACE );
  39395. let flipSided = ( material.side === BackSide );
  39396. if ( frontFaceCW ) flipSided = ! flipSided;
  39397. this.setFlipSided( flipSided );
  39398. ( material.blending === NormalBlending && material.transparent === false )
  39399. ? this.setBlending( NoBlending )
  39400. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39401. this.setDepthFunc( material.depthFunc );
  39402. this.setDepthTest( material.depthTest );
  39403. this.setDepthMask( material.depthWrite );
  39404. this.setColorMask( material.colorWrite );
  39405. const stencilWrite = material.stencilWrite;
  39406. this.setStencilTest( stencilWrite );
  39407. if ( stencilWrite ) {
  39408. this.setStencilMask( material.stencilWriteMask );
  39409. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39410. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39411. }
  39412. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39413. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39414. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39415. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39416. if ( hardwareClippingPlanes > 0 ) {
  39417. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  39418. const CLIP_DISTANCE0_WEBGL = 0x3000;
  39419. for ( let i = 0; i < 8; i ++ ) {
  39420. if ( i < hardwareClippingPlanes ) {
  39421. this.enable( CLIP_DISTANCE0_WEBGL + i );
  39422. } else {
  39423. this.disable( CLIP_DISTANCE0_WEBGL + i );
  39424. }
  39425. }
  39426. }
  39427. }
  39428. }
  39429. /**
  39430. * Specifies the polygon offset.
  39431. *
  39432. * This method caches the state so `gl.polygonOffset()` is only
  39433. * called when necessary.
  39434. *
  39435. * @param {Boolean} polygonOffset - Whether polygon offset is enabled or not.
  39436. * @param {Number} factor - The scale factor for the variable depth offset for each polygon.
  39437. * @param {Number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  39438. */
  39439. setPolygonOffset( polygonOffset, factor, units ) {
  39440. const { gl } = this;
  39441. if ( polygonOffset ) {
  39442. this.enable( gl.POLYGON_OFFSET_FILL );
  39443. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39444. gl.polygonOffset( factor, units );
  39445. this.currentPolygonOffsetFactor = factor;
  39446. this.currentPolygonOffsetUnits = units;
  39447. }
  39448. } else {
  39449. this.disable( gl.POLYGON_OFFSET_FILL );
  39450. }
  39451. }
  39452. /**
  39453. * Defines the usage of the given WebGL program.
  39454. *
  39455. * This method caches the state so `gl.useProgram()` is only
  39456. * called when necessary.
  39457. *
  39458. * @param {WebGLProgram} program - The WebGL program to use.
  39459. * @return {Boolean} Whether a program change has been executed or not.
  39460. */
  39461. useProgram( program ) {
  39462. if ( this.currentProgram !== program ) {
  39463. this.gl.useProgram( program );
  39464. this.currentProgram = program;
  39465. return true;
  39466. }
  39467. return false;
  39468. }
  39469. // framebuffer
  39470. /**
  39471. * Binds the given framebuffer.
  39472. *
  39473. * This method caches the state so `gl.bindFramebuffer()` is only
  39474. * called when necessary.
  39475. *
  39476. * @param {Number} target - The binding point (target).
  39477. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  39478. * @return {Boolean} Whether a bind has been executed or not.
  39479. */
  39480. bindFramebuffer( target, framebuffer ) {
  39481. const { gl, currentBoundFramebuffers } = this;
  39482. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39483. gl.bindFramebuffer( target, framebuffer );
  39484. currentBoundFramebuffers[ target ] = framebuffer;
  39485. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39486. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39487. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39488. }
  39489. if ( target === gl.FRAMEBUFFER ) {
  39490. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39491. }
  39492. return true;
  39493. }
  39494. return false;
  39495. }
  39496. /**
  39497. * Defines draw buffers to which fragment colors are written into.
  39498. * Configures the MRT setup of custom framebuffers.
  39499. *
  39500. * This method caches the state so `gl.drawBuffers()` is only
  39501. * called when necessary.
  39502. *
  39503. * @param {RenderContext} renderContext - The render context.
  39504. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  39505. */
  39506. drawBuffers( renderContext, framebuffer ) {
  39507. const { gl } = this;
  39508. let drawBuffers = [];
  39509. let needsUpdate = false;
  39510. if ( renderContext.textures !== null ) {
  39511. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39512. if ( drawBuffers === undefined ) {
  39513. drawBuffers = [];
  39514. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39515. }
  39516. const textures = renderContext.textures;
  39517. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39518. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39519. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39520. }
  39521. drawBuffers.length = textures.length;
  39522. needsUpdate = true;
  39523. }
  39524. } else {
  39525. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39526. drawBuffers[ 0 ] = gl.BACK;
  39527. needsUpdate = true;
  39528. }
  39529. }
  39530. if ( needsUpdate ) {
  39531. gl.drawBuffers( drawBuffers );
  39532. }
  39533. }
  39534. // texture
  39535. /**
  39536. * Makes the given texture unit active.
  39537. *
  39538. * This method caches the state so `gl.activeTexture()` is only
  39539. * called when necessary.
  39540. *
  39541. * @param {Number} webglSlot - The texture unit to make active.
  39542. */
  39543. activeTexture( webglSlot ) {
  39544. const { gl, currentTextureSlot, maxTextures } = this;
  39545. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39546. if ( currentTextureSlot !== webglSlot ) {
  39547. gl.activeTexture( webglSlot );
  39548. this.currentTextureSlot = webglSlot;
  39549. }
  39550. }
  39551. /**
  39552. * Binds the given WebGL texture to a target.
  39553. *
  39554. * This method caches the state so `gl.bindTexture()` is only
  39555. * called when necessary.
  39556. *
  39557. * @param {Number} webglType - The binding point (target).
  39558. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  39559. * @param {Number} webglSlot - The texture.
  39560. */
  39561. bindTexture( webglType, webglTexture, webglSlot ) {
  39562. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39563. if ( webglSlot === undefined ) {
  39564. if ( currentTextureSlot === null ) {
  39565. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39566. } else {
  39567. webglSlot = currentTextureSlot;
  39568. }
  39569. }
  39570. let boundTexture = currentBoundTextures[ webglSlot ];
  39571. if ( boundTexture === undefined ) {
  39572. boundTexture = { type: undefined, texture: undefined };
  39573. currentBoundTextures[ webglSlot ] = boundTexture;
  39574. }
  39575. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39576. if ( currentTextureSlot !== webglSlot ) {
  39577. gl.activeTexture( webglSlot );
  39578. this.currentTextureSlot = webglSlot;
  39579. }
  39580. gl.bindTexture( webglType, webglTexture );
  39581. boundTexture.type = webglType;
  39582. boundTexture.texture = webglTexture;
  39583. }
  39584. }
  39585. /**
  39586. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  39587. *
  39588. * This method caches the state so `gl.bindBufferBase()` is only
  39589. * called when necessary.
  39590. *
  39591. * @param {Number} target - The target for the bind operation.
  39592. * @param {Number} index - The index of the target.
  39593. * @param {WebGLBuffer} buffer - The WebGL buffer.
  39594. * @return {Boolean} Whether a bind has been executed or not.
  39595. */
  39596. bindBufferBase( target, index, buffer ) {
  39597. const { gl } = this;
  39598. const key = `${target}-${index}`;
  39599. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  39600. gl.bindBufferBase( target, index, buffer );
  39601. this.currentBoundBufferBases[ key ] = buffer;
  39602. return true;
  39603. }
  39604. return false;
  39605. }
  39606. /**
  39607. * Unbinds the current bound texture.
  39608. *
  39609. * This method caches the state so `gl.bindTexture()` is only
  39610. * called when necessary.
  39611. */
  39612. unbindTexture() {
  39613. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39614. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39615. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39616. gl.bindTexture( boundTexture.type, null );
  39617. boundTexture.type = undefined;
  39618. boundTexture.texture = undefined;
  39619. }
  39620. }
  39621. }
  39622. /**
  39623. * A WebGL 2 backend utility module with common helpers.
  39624. *
  39625. * @private
  39626. */
  39627. class WebGLUtils {
  39628. /**
  39629. * Constructs a new utility object.
  39630. *
  39631. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39632. */
  39633. constructor( backend ) {
  39634. /**
  39635. * A reference to the WebGL 2 backend.
  39636. *
  39637. * @type {WebGLBackend}
  39638. */
  39639. this.backend = backend;
  39640. /**
  39641. * A reference to the rendering context.
  39642. *
  39643. * @type {WebGL2RenderingContext}
  39644. */
  39645. this.gl = this.backend.gl;
  39646. /**
  39647. * A reference to a backend module holding extension-related
  39648. * utility functions.
  39649. *
  39650. * @type {WebGLExtensions}
  39651. */
  39652. this.extensions = backend.extensions;
  39653. }
  39654. /**
  39655. * Converts the given three.js constant into a WebGL constant.
  39656. * The method currently supports the conversion of texture formats
  39657. * and types.
  39658. *
  39659. * @param {Number} p - The three.js constant.
  39660. * @param {String} [colorSpace=NoColorSpace] - The color space.
  39661. * @return {Number} The corresponding WebGL constant.
  39662. */
  39663. convert( p, colorSpace = NoColorSpace ) {
  39664. const { gl, extensions } = this;
  39665. let extension;
  39666. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39667. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39668. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39669. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39670. if ( p === ByteType ) return gl.BYTE;
  39671. if ( p === ShortType ) return gl.SHORT;
  39672. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39673. if ( p === IntType ) return gl.INT;
  39674. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39675. if ( p === FloatType ) return gl.FLOAT;
  39676. if ( p === HalfFloatType ) {
  39677. return gl.HALF_FLOAT;
  39678. }
  39679. if ( p === AlphaFormat ) return gl.ALPHA;
  39680. if ( p === RGBFormat ) return gl.RGB;
  39681. if ( p === RGBAFormat ) return gl.RGBA;
  39682. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39683. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39684. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39685. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39686. // WebGL2 formats.
  39687. if ( p === RedFormat ) return gl.RED;
  39688. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39689. if ( p === RGFormat ) return gl.RG;
  39690. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39691. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39692. // S3TC
  39693. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39694. if ( colorSpace === SRGBColorSpace ) {
  39695. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39696. if ( extension !== null ) {
  39697. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39698. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39699. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39700. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39701. } else {
  39702. return null;
  39703. }
  39704. } else {
  39705. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39706. if ( extension !== null ) {
  39707. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39708. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39709. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39710. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39711. } else {
  39712. return null;
  39713. }
  39714. }
  39715. }
  39716. // PVRTC
  39717. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39718. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39719. if ( extension !== null ) {
  39720. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39721. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39722. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39723. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39724. } else {
  39725. return null;
  39726. }
  39727. }
  39728. // ETC
  39729. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39730. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39731. if ( extension !== null ) {
  39732. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39733. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39734. } else {
  39735. return null;
  39736. }
  39737. }
  39738. // ASTC
  39739. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39740. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39741. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39742. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39743. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39744. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39745. if ( extension !== null ) {
  39746. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39747. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39748. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39749. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39750. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39751. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39752. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39753. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39754. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39755. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39756. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39757. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39758. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39759. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39760. } else {
  39761. return null;
  39762. }
  39763. }
  39764. // BPTC
  39765. if ( p === RGBA_BPTC_Format ) {
  39766. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39767. if ( extension !== null ) {
  39768. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39769. } else {
  39770. return null;
  39771. }
  39772. }
  39773. // RGTC
  39774. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39775. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39776. if ( extension !== null ) {
  39777. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39778. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39779. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39780. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39781. } else {
  39782. return null;
  39783. }
  39784. }
  39785. //
  39786. if ( p === UnsignedInt248Type ) {
  39787. return gl.UNSIGNED_INT_24_8;
  39788. }
  39789. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39790. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39791. }
  39792. /**
  39793. * This method can be used to synchronize the CPU with the GPU by waiting until
  39794. * ongoing GPU commands have been completed.
  39795. *
  39796. * @private
  39797. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  39798. */
  39799. _clientWaitAsync() {
  39800. const { gl } = this;
  39801. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39802. gl.flush();
  39803. return new Promise( ( resolve, reject ) => {
  39804. function test() {
  39805. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39806. if ( res === gl.WAIT_FAILED ) {
  39807. gl.deleteSync( sync );
  39808. reject();
  39809. return;
  39810. }
  39811. if ( res === gl.TIMEOUT_EXPIRED ) {
  39812. requestAnimationFrame( test );
  39813. return;
  39814. }
  39815. gl.deleteSync( sync );
  39816. resolve();
  39817. }
  39818. test();
  39819. } );
  39820. }
  39821. }
  39822. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39823. /**
  39824. * A WebGL 2 backend utility module for managing textures.
  39825. *
  39826. * @private
  39827. */
  39828. class WebGLTextureUtils {
  39829. /**
  39830. * Constructs a new utility object.
  39831. *
  39832. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39833. */
  39834. constructor( backend ) {
  39835. /**
  39836. * A reference to the WebGL 2 backend.
  39837. *
  39838. * @type {WebGLBackend}
  39839. */
  39840. this.backend = backend;
  39841. /**
  39842. * A reference to the rendering context.
  39843. *
  39844. * @type {WebGL2RenderingContext}
  39845. */
  39846. this.gl = backend.gl;
  39847. /**
  39848. * A reference to a backend module holding extension-related
  39849. * utility functions.
  39850. *
  39851. * @type {WebGLExtensions}
  39852. */
  39853. this.extensions = backend.extensions;
  39854. /**
  39855. * A dictionary for managing default textures. The key
  39856. * is the binding point (target), the value the WEbGL texture object.
  39857. *
  39858. * @type {Object<GLenum,WebGLTexture>}
  39859. */
  39860. this.defaultTextures = {};
  39861. if ( initialized === false ) {
  39862. this._init();
  39863. initialized = true;
  39864. }
  39865. }
  39866. /**
  39867. * Inits the state of the utility.
  39868. *
  39869. * @private
  39870. */
  39871. _init() {
  39872. const gl = this.gl;
  39873. // Store only WebGL constants here.
  39874. wrappingToGL = {
  39875. [ RepeatWrapping ]: gl.REPEAT,
  39876. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39877. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39878. };
  39879. filterToGL = {
  39880. [ NearestFilter ]: gl.NEAREST,
  39881. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39882. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39883. [ LinearFilter ]: gl.LINEAR,
  39884. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39885. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39886. };
  39887. compareToGL = {
  39888. [ NeverCompare ]: gl.NEVER,
  39889. [ AlwaysCompare ]: gl.ALWAYS,
  39890. [ LessCompare ]: gl.LESS,
  39891. [ LessEqualCompare ]: gl.LEQUAL,
  39892. [ EqualCompare ]: gl.EQUAL,
  39893. [ GreaterEqualCompare ]: gl.GEQUAL,
  39894. [ GreaterCompare ]: gl.GREATER,
  39895. [ NotEqualCompare ]: gl.NOTEQUAL
  39896. };
  39897. }
  39898. /**
  39899. * Returns the native texture type for the given texture.
  39900. *
  39901. * @param {Texture} texture - The texture.
  39902. * @return {GLenum} The native texture type.
  39903. */
  39904. getGLTextureType( texture ) {
  39905. const { gl } = this;
  39906. let glTextureType;
  39907. if ( texture.isCubeTexture === true ) {
  39908. glTextureType = gl.TEXTURE_CUBE_MAP;
  39909. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39910. glTextureType = gl.TEXTURE_2D_ARRAY;
  39911. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  39912. glTextureType = gl.TEXTURE_3D;
  39913. } else {
  39914. glTextureType = gl.TEXTURE_2D;
  39915. }
  39916. return glTextureType;
  39917. }
  39918. /**
  39919. * Returns the native texture type for the given texture.
  39920. *
  39921. * @param {String?} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  39922. * @param {GLenum} glFormat - The WebGL format.
  39923. * @param {GLenum} glType - The WebGL type.
  39924. * @param {String} colorSpace - The texture's color space.
  39925. * @param {Boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  39926. * @return {GLenum} The internal format.
  39927. */
  39928. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39929. const { gl, extensions } = this;
  39930. if ( internalFormatName !== null ) {
  39931. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39932. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39933. }
  39934. let internalFormat = glFormat;
  39935. if ( glFormat === gl.RED ) {
  39936. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39937. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39938. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39939. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39940. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39941. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39942. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39943. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39944. }
  39945. if ( glFormat === gl.RED_INTEGER ) {
  39946. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39947. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39948. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39949. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39950. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39951. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39952. }
  39953. if ( glFormat === gl.RG ) {
  39954. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39955. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39956. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39957. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39958. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39959. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39960. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39961. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39962. }
  39963. if ( glFormat === gl.RG_INTEGER ) {
  39964. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39965. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39966. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39967. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39968. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39969. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39970. }
  39971. if ( glFormat === gl.RGB ) {
  39972. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39973. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39974. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39975. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39976. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39977. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39978. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39979. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39980. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39981. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  39982. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39983. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  39984. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  39985. }
  39986. if ( glFormat === gl.RGB_INTEGER ) {
  39987. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  39988. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  39989. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39990. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39991. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39992. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39993. }
  39994. if ( glFormat === gl.RGBA ) {
  39995. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  39996. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  39997. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  39998. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  39999. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40000. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40001. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40002. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40003. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40004. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40005. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40006. }
  40007. if ( glFormat === gl.RGBA_INTEGER ) {
  40008. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40009. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40010. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40011. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40012. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40013. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40014. }
  40015. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40016. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  40017. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  40018. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40019. }
  40020. if ( glFormat === gl.DEPTH_STENCIL ) {
  40021. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40022. }
  40023. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40024. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40025. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40026. extensions.get( 'EXT_color_buffer_float' );
  40027. }
  40028. return internalFormat;
  40029. }
  40030. /**
  40031. * Sets the texture parameters for the given texture.
  40032. *
  40033. * @param {GLenum} textureType - The texture type.
  40034. * @param {Texture} texture - The texture.
  40035. */
  40036. setTextureParameters( textureType, texture ) {
  40037. const { gl, extensions, backend } = this;
  40038. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40039. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40040. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40041. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40042. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40043. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40044. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40045. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40046. }
  40047. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40048. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40049. // follow WebGPU backend mapping for texture filtering
  40050. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40051. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40052. if ( texture.compareFunction ) {
  40053. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40054. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40055. }
  40056. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40057. if ( texture.magFilter === NearestFilter ) return;
  40058. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40059. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40060. if ( texture.anisotropy > 1 ) {
  40061. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40062. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40063. }
  40064. }
  40065. }
  40066. /**
  40067. * Creates a default texture for the given texture that can be used
  40068. * as a placeholder until the actual texture is ready for usage.
  40069. *
  40070. * @param {Texture} texture - The texture to create a default texture for.
  40071. */
  40072. createDefaultTexture( texture ) {
  40073. const { gl, backend, defaultTextures } = this;
  40074. const glTextureType = this.getGLTextureType( texture );
  40075. let textureGPU = defaultTextures[ glTextureType ];
  40076. if ( textureGPU === undefined ) {
  40077. textureGPU = gl.createTexture();
  40078. backend.state.bindTexture( glTextureType, textureGPU );
  40079. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40080. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40081. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40082. defaultTextures[ glTextureType ] = textureGPU;
  40083. }
  40084. backend.set( texture, {
  40085. textureGPU,
  40086. glTextureType,
  40087. isDefault: true
  40088. } );
  40089. }
  40090. /**
  40091. * Defines a texture on the GPU for the given texture object.
  40092. *
  40093. * @param {Texture} texture - The texture.
  40094. * @param {Object} [options={}] - Optional configuration parameter.
  40095. * @return {undefined}
  40096. */
  40097. createTexture( texture, options ) {
  40098. const { gl, backend } = this;
  40099. const { levels, width, height, depth } = options;
  40100. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40101. const glType = backend.utils.convert( texture.type );
  40102. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40103. const textureGPU = gl.createTexture();
  40104. const glTextureType = this.getGLTextureType( texture );
  40105. backend.state.bindTexture( glTextureType, textureGPU );
  40106. this.setTextureParameters( glTextureType, texture );
  40107. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40108. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40109. } else if ( texture.isData3DTexture ) {
  40110. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40111. } else if ( ! texture.isVideoTexture ) {
  40112. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40113. }
  40114. backend.set( texture, {
  40115. textureGPU,
  40116. glTextureType,
  40117. glFormat,
  40118. glType,
  40119. glInternalFormat
  40120. } );
  40121. }
  40122. /**
  40123. * Uploads texture buffer data to the GPU memory.
  40124. *
  40125. * @param {WebGLBuffer} buffer - The buffer data.
  40126. * @param {Texture} texture - The texture,
  40127. */
  40128. copyBufferToTexture( buffer, texture ) {
  40129. const { gl, backend } = this;
  40130. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40131. const { width, height } = texture.source.data;
  40132. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40133. backend.state.bindTexture( glTextureType, textureGPU );
  40134. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40135. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40136. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40137. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40138. backend.state.unbindTexture();
  40139. // debug
  40140. // const framebuffer = gl.createFramebuffer();
  40141. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40142. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40143. // const readout = new Float32Array( width * height * 4 );
  40144. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40145. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40146. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40147. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40148. // console.log( readout );
  40149. }
  40150. /**
  40151. * Uploads the updated texture data to the GPU.
  40152. *
  40153. * @param {Texture} texture - The texture.
  40154. * @param {Object} [options={}] - Optional configuration parameter.
  40155. */
  40156. updateTexture( texture, options ) {
  40157. const { gl } = this;
  40158. const { width, height } = options;
  40159. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40160. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40161. return;
  40162. const getImage = ( source ) => {
  40163. if ( source.isDataTexture ) {
  40164. return source.image.data;
  40165. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  40166. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  40167. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  40168. source instanceof OffscreenCanvas ) {
  40169. return source;
  40170. }
  40171. return source.data;
  40172. };
  40173. this.backend.state.bindTexture( glTextureType, textureGPU );
  40174. this.setTextureParameters( glTextureType, texture );
  40175. if ( texture.isCompressedTexture ) {
  40176. const mipmaps = texture.mipmaps;
  40177. const image = options.image;
  40178. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40179. const mipmap = mipmaps[ i ];
  40180. if ( texture.isCompressedArrayTexture ) {
  40181. if ( texture.format !== gl.RGBA ) {
  40182. if ( glFormat !== null ) {
  40183. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40184. } else {
  40185. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40186. }
  40187. } else {
  40188. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40189. }
  40190. } else {
  40191. if ( glFormat !== null ) {
  40192. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40193. } else {
  40194. console.warn( 'Unsupported compressed texture format' );
  40195. }
  40196. }
  40197. }
  40198. } else if ( texture.isCubeTexture ) {
  40199. const images = options.images;
  40200. for ( let i = 0; i < 6; i ++ ) {
  40201. const image = getImage( images[ i ] );
  40202. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40203. }
  40204. } else if ( texture.isDataArrayTexture ) {
  40205. const image = options.image;
  40206. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40207. } else if ( texture.isData3DTexture ) {
  40208. const image = options.image;
  40209. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40210. } else if ( texture.isVideoTexture ) {
  40211. texture.update();
  40212. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40213. } else {
  40214. const image = getImage( options.image );
  40215. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40216. }
  40217. }
  40218. /**
  40219. * Generates mipmaps for the given texture.
  40220. *
  40221. * @param {Texture} texture - The texture.
  40222. */
  40223. generateMipmaps( texture ) {
  40224. const { gl, backend } = this;
  40225. const { textureGPU, glTextureType } = backend.get( texture );
  40226. backend.state.bindTexture( glTextureType, textureGPU );
  40227. gl.generateMipmap( glTextureType );
  40228. }
  40229. /**
  40230. * Deallocates the render buffers of the given render target.
  40231. *
  40232. * @param {RenderTarget} renderTarget - The render target.
  40233. */
  40234. deallocateRenderBuffers( renderTarget ) {
  40235. const { gl, backend } = this;
  40236. // remove framebuffer reference
  40237. if ( renderTarget ) {
  40238. const renderContextData = backend.get( renderTarget );
  40239. renderContextData.renderBufferStorageSetup = undefined;
  40240. if ( renderContextData.framebuffers ) {
  40241. for ( const cacheKey in renderContextData.framebuffers ) {
  40242. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40243. }
  40244. delete renderContextData.framebuffers;
  40245. }
  40246. if ( renderContextData.depthRenderbuffer ) {
  40247. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40248. delete renderContextData.depthRenderbuffer;
  40249. }
  40250. if ( renderContextData.stencilRenderbuffer ) {
  40251. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40252. delete renderContextData.stencilRenderbuffer;
  40253. }
  40254. if ( renderContextData.msaaFrameBuffer ) {
  40255. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40256. delete renderContextData.msaaFrameBuffer;
  40257. }
  40258. if ( renderContextData.msaaRenderbuffers ) {
  40259. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40260. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40261. }
  40262. delete renderContextData.msaaRenderbuffers;
  40263. }
  40264. }
  40265. }
  40266. /**
  40267. * Destroys the GPU data for the given texture object.
  40268. *
  40269. * @param {Texture} texture - The texture.
  40270. */
  40271. destroyTexture( texture ) {
  40272. const { gl, backend } = this;
  40273. const { textureGPU, renderTarget } = backend.get( texture );
  40274. this.deallocateRenderBuffers( renderTarget );
  40275. gl.deleteTexture( textureGPU );
  40276. backend.delete( texture );
  40277. }
  40278. /**
  40279. * Copies data of the given source texture to the given destination texture.
  40280. *
  40281. * @param {Texture} srcTexture - The source texture.
  40282. * @param {Texture} dstTexture - The destination texture.
  40283. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  40284. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  40285. * @param {Number} [level=0] - The mip level to copy.
  40286. */
  40287. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40288. const { gl, backend } = this;
  40289. const { state } = this.backend;
  40290. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40291. let width, height, minX, minY;
  40292. let dstX, dstY;
  40293. if ( srcRegion !== null ) {
  40294. width = srcRegion.max.x - srcRegion.min.x;
  40295. height = srcRegion.max.y - srcRegion.min.y;
  40296. minX = srcRegion.min.x;
  40297. minY = srcRegion.min.y;
  40298. } else {
  40299. width = srcTexture.image.width;
  40300. height = srcTexture.image.height;
  40301. minX = 0;
  40302. minY = 0;
  40303. }
  40304. if ( dstPosition !== null ) {
  40305. dstX = dstPosition.x;
  40306. dstY = dstPosition.y;
  40307. } else {
  40308. dstX = 0;
  40309. dstY = 0;
  40310. }
  40311. state.bindTexture( glTextureType, dstTextureGPU );
  40312. // As another texture upload may have changed pixelStorei
  40313. // parameters, make sure they are correct for the dstTexture
  40314. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40315. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40316. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40317. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40318. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40319. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40320. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40321. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40322. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40323. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40324. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40325. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40326. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40327. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40328. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  40329. const srcTextureData = backend.get( srcTexture );
  40330. const dstTextureData = backend.get( dstTexture );
  40331. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  40332. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  40333. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  40334. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  40335. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  40336. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  40337. let mask = gl.COLOR_BUFFER_BIT;
  40338. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  40339. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  40340. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  40341. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  40342. } else {
  40343. if ( srcTexture.isDataTexture ) {
  40344. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40345. } else {
  40346. if ( srcTexture.isCompressedTexture ) {
  40347. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40348. } else {
  40349. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40350. }
  40351. }
  40352. }
  40353. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40354. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40355. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40356. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40357. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40358. // Generate mipmaps only when copying level 0
  40359. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40360. state.unbindTexture();
  40361. }
  40362. /**
  40363. * Copies the current bound framebuffer to the given texture.
  40364. *
  40365. * @param {Texture} texture - The destination texture.
  40366. * @param {RenderContext} renderContext - The render context.
  40367. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40368. */
  40369. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40370. const { gl } = this;
  40371. const { state } = this.backend;
  40372. const { textureGPU } = this.backend.get( texture );
  40373. const { x, y, z: width, w: height } = rectangle;
  40374. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40375. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  40376. if ( requireDrawFrameBuffer ) {
  40377. const partial = ( x !== 0 || y !== 0 );
  40378. let mask;
  40379. let attachment;
  40380. if ( texture.isDepthTexture === true ) {
  40381. mask = gl.DEPTH_BUFFER_BIT;
  40382. attachment = gl.DEPTH_ATTACHMENT;
  40383. if ( renderContext.stencil ) {
  40384. mask |= gl.STENCIL_BUFFER_BIT;
  40385. }
  40386. } else {
  40387. mask = gl.COLOR_BUFFER_BIT;
  40388. attachment = gl.COLOR_ATTACHMENT0;
  40389. }
  40390. if ( partial ) {
  40391. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40392. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40393. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40394. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40395. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40396. const flippedY = srcHeight - y - height;
  40397. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40398. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40399. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40400. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40401. state.unbindTexture();
  40402. } else {
  40403. const fb = gl.createFramebuffer();
  40404. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40405. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40406. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40407. gl.deleteFramebuffer( fb );
  40408. }
  40409. } else {
  40410. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40411. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40412. state.unbindTexture();
  40413. }
  40414. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40415. this.backend._setFramebuffer( renderContext );
  40416. }
  40417. /**
  40418. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  40419. *
  40420. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  40421. * @param {RenderContext} renderContext - The render context.
  40422. * @param {Number} samples - The MSAA sample count.
  40423. * @param {Boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  40424. */
  40425. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  40426. const { gl } = this;
  40427. const renderTarget = renderContext.renderTarget;
  40428. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40429. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40430. if ( depthBuffer && ! stencilBuffer ) {
  40431. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40432. if ( useMultisampledRTT === true ) {
  40433. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40434. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  40435. } else if ( samples > 0 ) {
  40436. if ( depthTexture && depthTexture.isDepthTexture ) {
  40437. if ( depthTexture.type === gl.FLOAT ) {
  40438. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40439. }
  40440. }
  40441. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40442. } else {
  40443. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40444. }
  40445. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40446. } else if ( depthBuffer && stencilBuffer ) {
  40447. if ( samples > 0 ) {
  40448. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40449. } else {
  40450. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40451. }
  40452. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40453. }
  40454. }
  40455. /**
  40456. * Returns texture data as a typed array.
  40457. *
  40458. * @async
  40459. * @param {Texture} texture - The texture to copy.
  40460. * @param {Number} x - The x coordinate of the copy origin.
  40461. * @param {Number} y - The y coordinate of the copy origin.
  40462. * @param {Number} width - The width of the copy.
  40463. * @param {Number} height - The height of the copy.
  40464. * @param {Number} faceIndex - The face index.
  40465. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40466. */
  40467. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40468. const { backend, gl } = this;
  40469. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40470. const fb = gl.createFramebuffer();
  40471. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40472. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40473. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40474. const typedArrayType = this._getTypedArrayType( glType );
  40475. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40476. const elementCount = width * height;
  40477. const byteLength = elementCount * bytesPerTexel;
  40478. const buffer = gl.createBuffer();
  40479. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40480. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40481. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40482. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40483. await backend.utils._clientWaitAsync();
  40484. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40485. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40486. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40487. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40488. gl.deleteFramebuffer( fb );
  40489. return dstBuffer;
  40490. }
  40491. /**
  40492. * Returns the corresponding typed array type for the given WebGL data type.
  40493. *
  40494. * @private
  40495. * @param {GLenum} glType - The WebGL data type.
  40496. * @return {TypedArray.constructor} The typed array type.
  40497. */
  40498. _getTypedArrayType( glType ) {
  40499. const { gl } = this;
  40500. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40501. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40502. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40503. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40504. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40505. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40506. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40507. if ( glType === gl.FLOAT ) return Float32Array;
  40508. throw new Error( `Unsupported WebGL type: ${glType}` );
  40509. }
  40510. /**
  40511. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  40512. *
  40513. * @private
  40514. * @param {GLenum} glType - The WebGL data type.
  40515. * @param {GLenum} glFormat - The WebGL texture format.
  40516. * @return {Number} The bytes-per-texel.
  40517. */
  40518. _getBytesPerTexel( glType, glFormat ) {
  40519. const { gl } = this;
  40520. let bytesPerComponent = 0;
  40521. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40522. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40523. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40524. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40525. glType === gl.UNSIGNED_SHORT ||
  40526. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40527. if ( glType === gl.UNSIGNED_INT ||
  40528. glType === gl.FLOAT ) bytesPerComponent = 4;
  40529. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40530. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40531. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40532. }
  40533. }
  40534. /**
  40535. * A WebGL 2 backend utility module for managing extensions.
  40536. *
  40537. * @private
  40538. */
  40539. class WebGLExtensions {
  40540. /**
  40541. * Constructs a new utility object.
  40542. *
  40543. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40544. */
  40545. constructor( backend ) {
  40546. /**
  40547. * A reference to the WebGL 2 backend.
  40548. *
  40549. * @type {WebGLBackend}
  40550. */
  40551. this.backend = backend;
  40552. /**
  40553. * A reference to the rendering context.
  40554. *
  40555. * @type {WebGL2RenderingContext}
  40556. */
  40557. this.gl = this.backend.gl;
  40558. /**
  40559. * A list with all the supported WebGL extensions.
  40560. *
  40561. * @type {Array<String>}
  40562. */
  40563. this.availableExtensions = this.gl.getSupportedExtensions();
  40564. /**
  40565. * A dictionary with requested WebGL extensions.
  40566. * The key is the name of the extension, the value
  40567. * the requested extension object.
  40568. *
  40569. * @type {Object<String,Object>}
  40570. */
  40571. this.extensions = {};
  40572. }
  40573. /**
  40574. * Returns the extension object for the given extension name.
  40575. *
  40576. * @param {String} name - The extension name.
  40577. * @return {Object} The extension object.
  40578. */
  40579. get( name ) {
  40580. let extension = this.extensions[ name ];
  40581. if ( extension === undefined ) {
  40582. extension = this.gl.getExtension( name );
  40583. this.extensions[ name ] = extension;
  40584. }
  40585. return extension;
  40586. }
  40587. /**
  40588. * Returns `true` if the requested extension is available.
  40589. *
  40590. * @param {String} name - The extension name.
  40591. * @return {Boolean} Whether the given extension is available or not.
  40592. */
  40593. has( name ) {
  40594. return this.availableExtensions.includes( name );
  40595. }
  40596. }
  40597. /**
  40598. * A WebGL 2 backend utility module for managing the device's capabilities.
  40599. *
  40600. * @private
  40601. */
  40602. class WebGLCapabilities {
  40603. /**
  40604. * Constructs a new utility object.
  40605. *
  40606. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40607. */
  40608. constructor( backend ) {
  40609. /**
  40610. * A reference to the WebGL 2 backend.
  40611. *
  40612. * @type {WebGLBackend}
  40613. */
  40614. this.backend = backend;
  40615. /**
  40616. * This value holds the cached max anisotropy value.
  40617. *
  40618. * @type {Number?}
  40619. * @default null
  40620. */
  40621. this.maxAnisotropy = null;
  40622. }
  40623. /**
  40624. * Returns the maximum anisotropy texture filtering value. This value
  40625. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  40626. * WebGL extension.
  40627. *
  40628. * @return {Number} The maximum anisotropy texture filtering value.
  40629. */
  40630. getMaxAnisotropy() {
  40631. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40632. const gl = this.backend.gl;
  40633. const extensions = this.backend.extensions;
  40634. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40635. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40636. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40637. } else {
  40638. this.maxAnisotropy = 0;
  40639. }
  40640. return this.maxAnisotropy;
  40641. }
  40642. }
  40643. const GLFeatureName = {
  40644. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40645. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40646. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40647. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40648. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40649. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40650. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40651. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40652. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40653. };
  40654. class WebGLBufferRenderer {
  40655. constructor( backend ) {
  40656. this.gl = backend.gl;
  40657. this.extensions = backend.extensions;
  40658. this.info = backend.renderer.info;
  40659. this.mode = null;
  40660. this.index = 0;
  40661. this.type = null;
  40662. this.object = null;
  40663. }
  40664. render( start, count ) {
  40665. const { gl, mode, object, type, info, index } = this;
  40666. if ( index !== 0 ) {
  40667. gl.drawElements( mode, count, type, start );
  40668. } else {
  40669. gl.drawArrays( mode, start, count );
  40670. }
  40671. info.update( object, count, mode, 1 );
  40672. }
  40673. renderInstances( start, count, primcount ) {
  40674. const { gl, mode, type, index, object, info } = this;
  40675. if ( primcount === 0 ) return;
  40676. if ( index !== 0 ) {
  40677. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40678. } else {
  40679. gl.drawArraysInstanced( mode, start, count, primcount );
  40680. }
  40681. info.update( object, count, mode, primcount );
  40682. }
  40683. renderMultiDraw( starts, counts, drawCount ) {
  40684. const { extensions, mode, object, info } = this;
  40685. if ( drawCount === 0 ) return;
  40686. const extension = extensions.get( 'WEBGL_multi_draw' );
  40687. if ( extension === null ) {
  40688. for ( let i = 0; i < drawCount; i ++ ) {
  40689. this.render( starts[ i ], counts[ i ] );
  40690. }
  40691. } else {
  40692. if ( this.index !== 0 ) {
  40693. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40694. } else {
  40695. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40696. }
  40697. let elementCount = 0;
  40698. for ( let i = 0; i < drawCount; i ++ ) {
  40699. elementCount += counts[ i ];
  40700. }
  40701. info.update( object, elementCount, mode, 1 );
  40702. }
  40703. }
  40704. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40705. const { extensions, mode, object, info } = this;
  40706. if ( drawCount === 0 ) return;
  40707. const extension = extensions.get( 'WEBGL_multi_draw' );
  40708. if ( extension === null ) {
  40709. for ( let i = 0; i < drawCount; i ++ ) {
  40710. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40711. }
  40712. } else {
  40713. if ( this.index !== 0 ) {
  40714. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40715. } else {
  40716. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40717. }
  40718. let elementCount = 0;
  40719. for ( let i = 0; i < drawCount; i ++ ) {
  40720. elementCount += counts[ i ] * primcount[ i ];
  40721. }
  40722. info.update( object, elementCount, mode, 1 );
  40723. }
  40724. }
  40725. //
  40726. }
  40727. class TimestampQueryPool {
  40728. constructor( maxQueries = 256 ) {
  40729. this.trackTimestamp = true;
  40730. this.maxQueries = maxQueries;
  40731. this.currentQueryIndex = 0; // how many queries allocated so far
  40732. this.queryOffsets = new Map(); // track offsets for different contexts
  40733. this.isDisposed = false;
  40734. this.lastValue = 0;
  40735. this.pendingResolve = false;
  40736. }
  40737. /**
  40738. * Allocate queries for a specific renderContext.
  40739. *
  40740. * @abstract
  40741. */
  40742. allocateQueriesForContext( /* renderContext */ ) {}
  40743. /**
  40744. * Resolve all timestamps and return data (or process them).
  40745. *
  40746. * @abstract
  40747. * @returns {Promise<Number>|Number} The resolved timestamp value.
  40748. */
  40749. async resolveQueriesAsync() {}
  40750. /**
  40751. * Dispose of the query pool.
  40752. *
  40753. * @abstract
  40754. */
  40755. dispose() {}
  40756. }
  40757. /**
  40758. * Manages a pool of WebGL timestamp queries for performance measurement.
  40759. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  40760. * @extends TimestampQueryPool
  40761. */
  40762. class WebGLTimestampQueryPool extends TimestampQueryPool {
  40763. /**
  40764. * Creates a new WebGL timestamp query pool.
  40765. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  40766. * @param {string} type - The type identifier for this query pool.
  40767. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  40768. */
  40769. constructor( gl, type, maxQueries = 2048 ) {
  40770. super( maxQueries );
  40771. this.gl = gl;
  40772. this.type = type;
  40773. // Check for timer query extensions
  40774. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  40775. gl.getExtension( 'EXT_disjoint_timer_query' );
  40776. if ( ! this.ext ) {
  40777. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  40778. this.trackTimestamp = false;
  40779. return;
  40780. }
  40781. // Create query objects
  40782. this.queries = [];
  40783. for ( let i = 0; i < this.maxQueries; i ++ ) {
  40784. this.queries.push( gl.createQuery() );
  40785. }
  40786. this.activeQuery = null;
  40787. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  40788. }
  40789. /**
  40790. * Allocates a pair of queries for a given render context.
  40791. * @param {Object} renderContext - The render context to allocate queries for.
  40792. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  40793. */
  40794. allocateQueriesForContext( renderContext ) {
  40795. if ( ! this.trackTimestamp ) return null;
  40796. // Check if we have enough space for a new query pair
  40797. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  40798. 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() } ).` );
  40799. return null;
  40800. }
  40801. const baseOffset = this.currentQueryIndex;
  40802. this.currentQueryIndex += 2;
  40803. // Initialize query states
  40804. this.queryStates.set( baseOffset, 'inactive' );
  40805. this.queryOffsets.set( renderContext.id, baseOffset );
  40806. return baseOffset;
  40807. }
  40808. /**
  40809. * Begins a timestamp query for the specified render context.
  40810. * @param {Object} renderContext - The render context to begin timing for.
  40811. */
  40812. beginQuery( renderContext ) {
  40813. if ( ! this.trackTimestamp || this.isDisposed ) {
  40814. return;
  40815. }
  40816. const baseOffset = this.queryOffsets.get( renderContext.id );
  40817. if ( baseOffset == null ) {
  40818. return;
  40819. }
  40820. // Don't start a new query if there's an active one
  40821. if ( this.activeQuery !== null ) {
  40822. return;
  40823. }
  40824. const query = this.queries[ baseOffset ];
  40825. if ( ! query ) {
  40826. return;
  40827. }
  40828. try {
  40829. // Only begin if query is inactive
  40830. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  40831. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  40832. this.activeQuery = baseOffset;
  40833. this.queryStates.set( baseOffset, 'started' );
  40834. }
  40835. } catch ( error ) {
  40836. console.error( 'Error in beginQuery:', error );
  40837. this.activeQuery = null;
  40838. this.queryStates.set( baseOffset, 'inactive' );
  40839. }
  40840. }
  40841. /**
  40842. * Ends the active timestamp query for the specified render context.
  40843. * @param {Object} renderContext - The render context to end timing for.
  40844. * @param {string} renderContext.id - Unique identifier for the render context.
  40845. */
  40846. endQuery( renderContext ) {
  40847. if ( ! this.trackTimestamp || this.isDisposed ) {
  40848. return;
  40849. }
  40850. const baseOffset = this.queryOffsets.get( renderContext.id );
  40851. if ( baseOffset == null ) {
  40852. return;
  40853. }
  40854. // Only end if this is the active query
  40855. if ( this.activeQuery !== baseOffset ) {
  40856. return;
  40857. }
  40858. try {
  40859. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  40860. this.queryStates.set( baseOffset, 'ended' );
  40861. this.activeQuery = null;
  40862. } catch ( error ) {
  40863. console.error( 'Error in endQuery:', error );
  40864. // Reset state on error
  40865. this.queryStates.set( baseOffset, 'inactive' );
  40866. this.activeQuery = null;
  40867. }
  40868. }
  40869. /**
  40870. * Asynchronously resolves all completed queries and returns the total duration.
  40871. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  40872. */
  40873. async resolveQueriesAsync() {
  40874. if ( ! this.trackTimestamp || this.pendingResolve ) {
  40875. return this.lastValue;
  40876. }
  40877. this.pendingResolve = true;
  40878. try {
  40879. // Wait for all ended queries to complete
  40880. const resolvePromises = [];
  40881. for ( const [ baseOffset, state ] of this.queryStates ) {
  40882. if ( state === 'ended' ) {
  40883. const query = this.queries[ baseOffset ];
  40884. resolvePromises.push( this.resolveQuery( query ) );
  40885. }
  40886. }
  40887. if ( resolvePromises.length === 0 ) {
  40888. return this.lastValue;
  40889. }
  40890. const results = await Promise.all( resolvePromises );
  40891. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  40892. // Store the last valid result
  40893. this.lastValue = totalDuration;
  40894. // Reset states
  40895. this.currentQueryIndex = 0;
  40896. this.queryOffsets.clear();
  40897. this.queryStates.clear();
  40898. this.activeQuery = null;
  40899. return totalDuration;
  40900. } catch ( error ) {
  40901. console.error( 'Error resolving queries:', error );
  40902. return this.lastValue;
  40903. } finally {
  40904. this.pendingResolve = false;
  40905. }
  40906. }
  40907. /**
  40908. * Resolves a single query, checking for completion and disjoint operation.
  40909. * @private
  40910. * @param {WebGLQuery} query - The query object to resolve.
  40911. * @returns {Promise<number>} The elapsed time in milliseconds.
  40912. */
  40913. async resolveQuery( query ) {
  40914. return new Promise( ( resolve ) => {
  40915. if ( this.isDisposed ) {
  40916. resolve( this.lastValue );
  40917. return;
  40918. }
  40919. let timeoutId;
  40920. let isResolved = false;
  40921. const cleanup = () => {
  40922. if ( timeoutId ) {
  40923. clearTimeout( timeoutId );
  40924. timeoutId = null;
  40925. }
  40926. };
  40927. const finalizeResolution = ( value ) => {
  40928. if ( ! isResolved ) {
  40929. isResolved = true;
  40930. cleanup();
  40931. resolve( value );
  40932. }
  40933. };
  40934. const checkQuery = () => {
  40935. if ( this.isDisposed ) {
  40936. finalizeResolution( this.lastValue );
  40937. return;
  40938. }
  40939. try {
  40940. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  40941. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  40942. if ( disjoint ) {
  40943. finalizeResolution( this.lastValue );
  40944. return;
  40945. }
  40946. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  40947. if ( ! available ) {
  40948. timeoutId = setTimeout( checkQuery, 1 );
  40949. return;
  40950. }
  40951. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  40952. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  40953. } catch ( error ) {
  40954. console.error( 'Error checking query:', error );
  40955. resolve( this.lastValue );
  40956. }
  40957. };
  40958. checkQuery();
  40959. } );
  40960. }
  40961. /**
  40962. * Releases all resources held by this query pool.
  40963. * This includes deleting all query objects and clearing internal state.
  40964. */
  40965. dispose() {
  40966. if ( this.isDisposed ) {
  40967. return;
  40968. }
  40969. this.isDisposed = true;
  40970. if ( ! this.trackTimestamp ) return;
  40971. for ( const query of this.queries ) {
  40972. this.gl.deleteQuery( query );
  40973. }
  40974. this.queries = [];
  40975. this.queryStates.clear();
  40976. this.queryOffsets.clear();
  40977. this.lastValue = 0;
  40978. this.activeQuery = null;
  40979. }
  40980. }
  40981. /**
  40982. * A backend implementation targeting WebGL 2.
  40983. *
  40984. * @private
  40985. * @augments Backend
  40986. */
  40987. class WebGLBackend extends Backend {
  40988. /**
  40989. * Constructs a new WebGPU backend.
  40990. *
  40991. * @param {Object} parameters - The configuration parameter.
  40992. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40993. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40994. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40995. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40996. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40997. * @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.
  40998. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  40999. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  41000. */
  41001. constructor( parameters = {} ) {
  41002. super( parameters );
  41003. /**
  41004. * This flag can be used for type testing.
  41005. *
  41006. * @type {Boolean}
  41007. * @readonly
  41008. * @default true
  41009. */
  41010. this.isWebGLBackend = true;
  41011. /**
  41012. * A reference to a backend module holding shader attribute-related
  41013. * utility functions.
  41014. *
  41015. * @type {WebGLAttributeUtils?}
  41016. * @default null
  41017. */
  41018. this.attributeUtils = null;
  41019. /**
  41020. * A reference to a backend module holding extension-related
  41021. * utility functions.
  41022. *
  41023. * @type {WebGLExtensions?}
  41024. * @default null
  41025. */
  41026. this.extensions = null;
  41027. /**
  41028. * A reference to a backend module holding capability-related
  41029. * utility functions.
  41030. *
  41031. * @type {WebGLCapabilities?}
  41032. * @default null
  41033. */
  41034. this.capabilities = null;
  41035. /**
  41036. * A reference to a backend module holding texture-related
  41037. * utility functions.
  41038. *
  41039. * @type {WebGLTextureUtils?}
  41040. * @default null
  41041. */
  41042. this.textureUtils = null;
  41043. /**
  41044. * A reference to a backend module holding renderer-related
  41045. * utility functions.
  41046. *
  41047. * @type {WebGLBufferRenderer?}
  41048. * @default null
  41049. */
  41050. this.bufferRenderer = null;
  41051. /**
  41052. * A reference to the rendering context.
  41053. *
  41054. * @type {WebGL2RenderingContext?}
  41055. * @default null
  41056. */
  41057. this.gl = null;
  41058. /**
  41059. * A reference to a backend module holding state-related
  41060. * utility functions.
  41061. *
  41062. * @type {WebGLState?}
  41063. * @default null
  41064. */
  41065. this.state = null;
  41066. /**
  41067. * A reference to a backend module holding common
  41068. * utility functions.
  41069. *
  41070. * @type {WebGLUtils?}
  41071. * @default null
  41072. */
  41073. this.utils = null;
  41074. /**
  41075. * Dictionary for caching VAOs.
  41076. *
  41077. * @type {Object<String,WebGLVertexArrayObject>}
  41078. */
  41079. this.vaoCache = {};
  41080. /**
  41081. * Dictionary for caching transform feedback objects.
  41082. *
  41083. * @type {Object<String,WebGLTransformFeedback>}
  41084. */
  41085. this.transformFeedbackCache = {};
  41086. /**
  41087. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  41088. * Only relevant when using compute shaders.
  41089. *
  41090. * @type {Boolean}
  41091. * @default false
  41092. */
  41093. this.discard = false;
  41094. /**
  41095. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  41096. * device does not support the extension.
  41097. *
  41098. * @type {EXTDisjointTimerQueryWebGL2?}
  41099. * @default null
  41100. */
  41101. this.disjoint = null;
  41102. /**
  41103. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  41104. * device does not support the extension.
  41105. *
  41106. * @type {KHRParallelShaderCompile?}
  41107. * @default null
  41108. */
  41109. this.parallel = null;
  41110. /**
  41111. * Whether to track timestamps with a Timestamp Query API or not.
  41112. *
  41113. * @type {Boolean}
  41114. * @default false
  41115. */
  41116. this.trackTimestamp = ( parameters.trackTimestamp === true );
  41117. /**
  41118. * A reference to the current render context.
  41119. *
  41120. * @private
  41121. * @type {RenderContext}
  41122. * @default null
  41123. */
  41124. this._currentContext = null;
  41125. /**
  41126. * A unique collection of bindings.
  41127. *
  41128. * @private
  41129. * @type {WeakSet}
  41130. */
  41131. this._knownBindings = new WeakSet();
  41132. /**
  41133. * The target framebuffer when rendering with
  41134. * the WebXR device API.
  41135. *
  41136. * @private
  41137. * @type {WebGLFramebuffer}
  41138. * @default null
  41139. */
  41140. this._xrFamebuffer = null;
  41141. }
  41142. /**
  41143. * Initializes the backend so it is ready for usage.
  41144. *
  41145. * @param {Renderer} renderer - The renderer.
  41146. */
  41147. init( renderer ) {
  41148. super.init( renderer );
  41149. //
  41150. const parameters = this.parameters;
  41151. const contextAttributes = {
  41152. antialias: false, // MSAA is applied via a custom renderbuffer
  41153. alpha: true, // always true for performance reasons
  41154. depth: false, // depth and stencil are set to false since the engine always renders into a framebuffer target first
  41155. stencil: false
  41156. };
  41157. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  41158. function onContextLost( event ) {
  41159. event.preventDefault();
  41160. const contextLossInfo = {
  41161. api: 'WebGL',
  41162. message: event.statusMessage || 'Unknown reason',
  41163. reason: null,
  41164. originalEvent: event
  41165. };
  41166. renderer.onDeviceLost( contextLossInfo );
  41167. }
  41168. this._onContextLost = onContextLost;
  41169. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  41170. this.gl = glContext;
  41171. this.extensions = new WebGLExtensions( this );
  41172. this.capabilities = new WebGLCapabilities( this );
  41173. this.attributeUtils = new WebGLAttributeUtils( this );
  41174. this.textureUtils = new WebGLTextureUtils( this );
  41175. this.bufferRenderer = new WebGLBufferRenderer( this );
  41176. this.state = new WebGLState( this );
  41177. this.utils = new WebGLUtils( this );
  41178. this.extensions.get( 'EXT_color_buffer_float' );
  41179. this.extensions.get( 'WEBGL_clip_cull_distance' );
  41180. this.extensions.get( 'OES_texture_float_linear' );
  41181. this.extensions.get( 'EXT_color_buffer_half_float' );
  41182. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  41183. this.extensions.get( 'WEBGL_render_shared_exponent' );
  41184. this.extensions.get( 'WEBGL_multi_draw' );
  41185. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  41186. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  41187. }
  41188. /**
  41189. * The coordinate system of the backend.
  41190. *
  41191. * @type {Number}
  41192. * @readonly
  41193. */
  41194. get coordinateSystem() {
  41195. return WebGLCoordinateSystem;
  41196. }
  41197. /**
  41198. * This method performs a readback operation by moving buffer data from
  41199. * a storage buffer attribute from the GPU to the CPU.
  41200. *
  41201. * @async
  41202. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41203. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41204. */
  41205. async getArrayBufferAsync( attribute ) {
  41206. return await this.attributeUtils.getArrayBufferAsync( attribute );
  41207. }
  41208. /**
  41209. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41210. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41211. *
  41212. * @async
  41213. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41214. */
  41215. async waitForGPU() {
  41216. await this.utils._clientWaitAsync();
  41217. }
  41218. /**
  41219. * Ensures the backend is XR compatible.
  41220. *
  41221. * @async
  41222. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  41223. */
  41224. async makeXRCompatible() {
  41225. const attributes = this.gl.getContextAttributes();
  41226. if ( attributes.xrCompatible !== true ) {
  41227. await this.gl.makeXRCompatible();
  41228. }
  41229. }
  41230. /**
  41231. * Sets the XR rendering destination.
  41232. *
  41233. * @param {WebGLFramebuffer} xrFamebuffer - The XR framebuffer.
  41234. */
  41235. setXRTarget( xrFamebuffer ) {
  41236. this._xrFamebuffer = xrFamebuffer;
  41237. }
  41238. /**
  41239. * Configures the given XR render target with external textures.
  41240. *
  41241. * This method is only relevant when using the WebXR Layers API.
  41242. *
  41243. * @param {XRRenderTarget} renderTarget - The XR render target.
  41244. * @param {WebGLTexture} colorTexture - A native color texture.
  41245. * @param {WebGLTexture?} [depthTexture=null] - A native depth texture.
  41246. */
  41247. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  41248. const gl = this.gl;
  41249. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  41250. if ( depthTexture !== null ) {
  41251. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  41252. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  41253. renderTarget.autoAllocateDepthBuffer = false;
  41254. // The multisample_render_to_texture extension doesn't work properly if there
  41255. // are midframe flushes and an external depth texture.
  41256. if ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  41257. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  41258. }
  41259. }
  41260. }
  41261. /**
  41262. * Inits a time stamp query for the given render context.
  41263. *
  41264. * @param {RenderContext} renderContext - The render context.
  41265. */
  41266. initTimestampQuery( renderContext ) {
  41267. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41268. const type = renderContext.isComputeNode ? 'compute' : 'render';
  41269. if ( ! this.timestampQueryPool[ type ] ) {
  41270. // TODO: Variable maxQueries?
  41271. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  41272. }
  41273. const timestampQueryPool = this.timestampQueryPool[ type ];
  41274. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  41275. if ( baseOffset !== null ) {
  41276. timestampQueryPool.beginQuery( renderContext );
  41277. }
  41278. }
  41279. // timestamp utils
  41280. /**
  41281. * Prepares the timestamp buffer.
  41282. *
  41283. * @param {RenderContext} renderContext - The render context.
  41284. */
  41285. prepareTimestampBuffer( renderContext ) {
  41286. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  41287. const type = renderContext.isComputeNode ? 'compute' : 'render';
  41288. const timestampQueryPool = this.timestampQueryPool[ type ];
  41289. timestampQueryPool.endQuery( renderContext );
  41290. }
  41291. /**
  41292. * Returns the backend's rendering context.
  41293. *
  41294. * @return {WebGL2RenderingContext} The rendering context.
  41295. */
  41296. getContext() {
  41297. return this.gl;
  41298. }
  41299. /**
  41300. * This method is executed at the beginning of a render call and prepares
  41301. * the WebGL state for upcoming render calls
  41302. *
  41303. * @param {RenderContext} renderContext - The render context.
  41304. */
  41305. beginRender( renderContext ) {
  41306. const { state, gl } = this;
  41307. const renderContextData = this.get( renderContext );
  41308. //
  41309. //
  41310. this.initTimestampQuery( renderContext );
  41311. renderContextData.previousContext = this._currentContext;
  41312. this._currentContext = renderContext;
  41313. this._setFramebuffer( renderContext );
  41314. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  41315. //
  41316. if ( renderContext.viewport ) {
  41317. this.updateViewport( renderContext );
  41318. } else {
  41319. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41320. }
  41321. if ( renderContext.scissor ) {
  41322. const { x, y, width, height } = renderContext.scissorValue;
  41323. state.scissor( x, renderContext.height - height - y, width, height );
  41324. }
  41325. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41326. if ( occlusionQueryCount > 0 ) {
  41327. // Get a reference to the array of objects with queries. The renderContextData property
  41328. // can be changed by another render pass before the async reading of all previous queries complete
  41329. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  41330. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  41331. renderContextData.lastOcclusionObject = null;
  41332. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  41333. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  41334. renderContextData.occlusionQueryIndex = 0;
  41335. }
  41336. }
  41337. /**
  41338. * This method is executed at the end of a render call and finalizes work
  41339. * after draw calls.
  41340. *
  41341. * @param {RenderContext} renderContext - The render context.
  41342. */
  41343. finishRender( renderContext ) {
  41344. const { gl, state } = this;
  41345. const renderContextData = this.get( renderContext );
  41346. const previousContext = renderContextData.previousContext;
  41347. const occlusionQueryCount = renderContext.occlusionQueryCount;
  41348. if ( occlusionQueryCount > 0 ) {
  41349. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  41350. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41351. }
  41352. this.resolveOccludedAsync( renderContext );
  41353. }
  41354. const textures = renderContext.textures;
  41355. if ( textures !== null ) {
  41356. for ( let i = 0; i < textures.length; i ++ ) {
  41357. const texture = textures[ i ];
  41358. if ( texture.generateMipmaps ) {
  41359. this.generateMipmaps( texture );
  41360. }
  41361. }
  41362. }
  41363. this._currentContext = previousContext;
  41364. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  41365. const renderTargetContextData = this.get( renderContext.renderTarget );
  41366. const { samples } = renderContext.renderTarget;
  41367. if ( samples > 0 && this._useMultisampledRTT( renderContext.renderTarget ) === false ) {
  41368. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41369. const mask = gl.COLOR_BUFFER_BIT;
  41370. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41371. const textures = renderContext.textures;
  41372. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41373. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41374. for ( let i = 0; i < textures.length; i ++ ) {
  41375. // TODO Add support for MRT
  41376. if ( renderContext.scissor ) {
  41377. const { x, y, width, height } = renderContext.scissorValue;
  41378. const viewY = renderContext.height - height - y;
  41379. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  41380. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  41381. } else {
  41382. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  41383. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  41384. }
  41385. }
  41386. }
  41387. }
  41388. if ( previousContext !== null ) {
  41389. this._setFramebuffer( previousContext );
  41390. if ( previousContext.viewport ) {
  41391. this.updateViewport( previousContext );
  41392. } else {
  41393. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  41394. }
  41395. }
  41396. this.prepareTimestampBuffer( renderContext );
  41397. }
  41398. /**
  41399. * This method processes the result of occlusion queries and writes it
  41400. * into render context data.
  41401. *
  41402. * @async
  41403. * @param {RenderContext} renderContext - The render context.
  41404. */
  41405. resolveOccludedAsync( renderContext ) {
  41406. const renderContextData = this.get( renderContext );
  41407. // handle occlusion query results
  41408. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  41409. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  41410. const occluded = new WeakSet();
  41411. const { gl } = this;
  41412. renderContextData.currentOcclusionQueryObjects = null;
  41413. renderContextData.currentOcclusionQueries = null;
  41414. const check = () => {
  41415. let completed = 0;
  41416. // check all queries and requeue as appropriate
  41417. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  41418. const query = currentOcclusionQueries[ i ];
  41419. if ( query === null ) continue;
  41420. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  41421. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  41422. currentOcclusionQueries[ i ] = null;
  41423. gl.deleteQuery( query );
  41424. completed ++;
  41425. }
  41426. }
  41427. if ( completed < currentOcclusionQueries.length ) {
  41428. requestAnimationFrame( check );
  41429. } else {
  41430. renderContextData.occluded = occluded;
  41431. }
  41432. };
  41433. check();
  41434. }
  41435. }
  41436. /**
  41437. * Returns `true` if the given 3D object is fully occluded by other
  41438. * 3D objects in the scene.
  41439. *
  41440. * @param {RenderContext} renderContext - The render context.
  41441. * @param {Object3D} object - The 3D object to test.
  41442. * @return {Boolean} Whether the 3D object is fully occluded or not.
  41443. */
  41444. isOccluded( renderContext, object ) {
  41445. const renderContextData = this.get( renderContext );
  41446. return renderContextData.occluded && renderContextData.occluded.has( object );
  41447. }
  41448. /**
  41449. * Updates the viewport with the values from the given render context.
  41450. *
  41451. * @param {RenderContext} renderContext - The render context.
  41452. */
  41453. updateViewport( renderContext ) {
  41454. const { state } = this;
  41455. const { x, y, width, height } = renderContext.viewportValue;
  41456. state.viewport( x, renderContext.height - height - y, width, height );
  41457. }
  41458. /**
  41459. * Defines the scissor test.
  41460. *
  41461. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  41462. */
  41463. setScissorTest( boolean ) {
  41464. const state = this.state;
  41465. state.setScissorTest( boolean );
  41466. }
  41467. /**
  41468. * Performs a clear operation.
  41469. *
  41470. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  41471. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  41472. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  41473. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  41474. * @param {Boolean} [setFrameBuffer=true] - TODO.
  41475. */
  41476. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  41477. const { gl } = this;
  41478. if ( descriptor === null ) {
  41479. const clearColor = this.getClearColor();
  41480. // premultiply alpha
  41481. clearColor.r *= clearColor.a;
  41482. clearColor.g *= clearColor.a;
  41483. clearColor.b *= clearColor.a;
  41484. descriptor = {
  41485. textures: null,
  41486. clearColorValue: clearColor
  41487. };
  41488. }
  41489. //
  41490. let clear = 0;
  41491. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  41492. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  41493. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  41494. if ( clear !== 0 ) {
  41495. let clearColor;
  41496. if ( descriptor.clearColorValue ) {
  41497. clearColor = descriptor.clearColorValue;
  41498. } else {
  41499. clearColor = this.getClearColor();
  41500. // premultiply alpha
  41501. clearColor.r *= clearColor.a;
  41502. clearColor.g *= clearColor.a;
  41503. clearColor.b *= clearColor.a;
  41504. }
  41505. if ( depth ) this.state.setDepthMask( true );
  41506. if ( descriptor.textures === null ) {
  41507. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  41508. gl.clear( clear );
  41509. } else {
  41510. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  41511. if ( color ) {
  41512. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  41513. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  41514. }
  41515. }
  41516. if ( depth && stencil ) {
  41517. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  41518. } else if ( depth ) {
  41519. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  41520. } else if ( stencil ) {
  41521. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  41522. }
  41523. }
  41524. }
  41525. }
  41526. /**
  41527. * This method is executed at the beginning of a compute call and
  41528. * prepares the state for upcoming compute tasks.
  41529. *
  41530. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41531. */
  41532. beginCompute( computeGroup ) {
  41533. const { state, gl } = this;
  41534. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  41535. this.initTimestampQuery( computeGroup );
  41536. }
  41537. /**
  41538. * Executes a compute command for the given compute node.
  41539. *
  41540. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  41541. * @param {Node} computeNode - The compute node.
  41542. * @param {Array<BindGroup>} bindings - The bindings.
  41543. * @param {ComputePipeline} pipeline - The compute pipeline.
  41544. */
  41545. compute( computeGroup, computeNode, bindings, pipeline ) {
  41546. const { state, gl } = this;
  41547. if ( this.discard === false ) {
  41548. // required here to handle async behaviour of render.compute()
  41549. gl.enable( gl.RASTERIZER_DISCARD );
  41550. this.discard = true;
  41551. }
  41552. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  41553. const vaoKey = this._getVaoKey( null, attributes );
  41554. const vaoGPU = this.vaoCache[ vaoKey ];
  41555. if ( vaoGPU === undefined ) {
  41556. this._createVao( null, attributes );
  41557. } else {
  41558. gl.bindVertexArray( vaoGPU );
  41559. }
  41560. state.useProgram( programGPU );
  41561. this._bindUniforms( bindings );
  41562. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  41563. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41564. gl.beginTransformFeedback( gl.POINTS );
  41565. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  41566. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  41567. } else {
  41568. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  41569. }
  41570. gl.endTransformFeedback();
  41571. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41572. // switch active buffers
  41573. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41574. const dualAttributeData = transformBuffers[ i ];
  41575. if ( dualAttributeData.pbo ) {
  41576. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  41577. }
  41578. dualAttributeData.switchBuffers();
  41579. }
  41580. }
  41581. /**
  41582. * This method is executed at the end of a compute call and
  41583. * finalizes work after compute tasks.
  41584. *
  41585. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41586. */
  41587. finishCompute( computeGroup ) {
  41588. const gl = this.gl;
  41589. this.discard = false;
  41590. gl.disable( gl.RASTERIZER_DISCARD );
  41591. this.prepareTimestampBuffer( computeGroup );
  41592. if ( this._currentContext ) {
  41593. this._setFramebuffer( this._currentContext );
  41594. }
  41595. }
  41596. /**
  41597. * Executes a draw command for the given render object.
  41598. *
  41599. * @param {RenderObject} renderObject - The render object to draw.
  41600. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  41601. */
  41602. draw( renderObject/*, info*/ ) {
  41603. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  41604. const { programGPU } = this.get( pipeline );
  41605. const { gl, state } = this;
  41606. const contextData = this.get( context );
  41607. const drawParams = renderObject.getDrawParameters();
  41608. if ( drawParams === null ) return;
  41609. //
  41610. this._bindUniforms( renderObject.getBindings() );
  41611. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  41612. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  41613. state.useProgram( programGPU );
  41614. //
  41615. const renderObjectData = this.get( renderObject );
  41616. let vaoGPU = renderObjectData.staticVao;
  41617. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  41618. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  41619. vaoGPU = this.vaoCache[ vaoKey ];
  41620. if ( vaoGPU === undefined ) {
  41621. let staticVao;
  41622. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  41623. if ( staticVao ) {
  41624. renderObjectData.staticVao = vaoGPU;
  41625. renderObjectData.geometryId = renderObject.geometry.id;
  41626. }
  41627. }
  41628. }
  41629. gl.bindVertexArray( vaoGPU );
  41630. //
  41631. const index = renderObject.getIndex();
  41632. //
  41633. const lastObject = contextData.lastOcclusionObject;
  41634. if ( lastObject !== object && lastObject !== undefined ) {
  41635. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  41636. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  41637. contextData.occlusionQueryIndex ++;
  41638. }
  41639. if ( object.occlusionTest === true ) {
  41640. const query = gl.createQuery();
  41641. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  41642. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  41643. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  41644. }
  41645. contextData.lastOcclusionObject = object;
  41646. }
  41647. //
  41648. const renderer = this.bufferRenderer;
  41649. if ( object.isPoints ) renderer.mode = gl.POINTS;
  41650. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  41651. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  41652. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  41653. else {
  41654. if ( material.wireframe === true ) {
  41655. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  41656. renderer.mode = gl.LINES;
  41657. } else {
  41658. renderer.mode = gl.TRIANGLES;
  41659. }
  41660. }
  41661. //
  41662. const { vertexCount, instanceCount } = drawParams;
  41663. let { firstVertex } = drawParams;
  41664. renderer.object = object;
  41665. if ( index !== null ) {
  41666. firstVertex *= index.array.BYTES_PER_ELEMENT;
  41667. const indexData = this.get( index );
  41668. renderer.index = index.count;
  41669. renderer.type = indexData.type;
  41670. } else {
  41671. renderer.index = 0;
  41672. }
  41673. const draw = () => {
  41674. if ( object.isBatchedMesh ) {
  41675. if ( object._multiDrawInstances !== null ) {
  41676. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  41677. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  41678. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  41679. } else {
  41680. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  41681. }
  41682. } else if ( instanceCount > 1 ) {
  41683. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  41684. } else {
  41685. renderer.render( firstVertex, vertexCount );
  41686. }
  41687. };
  41688. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  41689. const cameraData = this.get( renderObject.camera );
  41690. const cameras = renderObject.camera.cameras;
  41691. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  41692. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  41693. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  41694. const indexesGPU = [];
  41695. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  41696. const bufferGPU = gl.createBuffer();
  41697. data[ 0 ] = i;
  41698. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41699. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  41700. indexesGPU.push( bufferGPU );
  41701. }
  41702. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  41703. }
  41704. const cameraIndexData = this.get( cameraIndex );
  41705. const pixelRatio = this.renderer.getPixelRatio();
  41706. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  41707. const subCamera = cameras[ i ];
  41708. if ( object.layers.test( subCamera.layers ) ) {
  41709. const vp = subCamera.viewport;
  41710. const x = vp.x * pixelRatio;
  41711. const y = vp.y * pixelRatio;
  41712. const width = vp.width * pixelRatio;
  41713. const height = vp.height * pixelRatio;
  41714. state.viewport(
  41715. Math.floor( x ),
  41716. Math.floor( renderObject.context.height - height - y ),
  41717. Math.floor( width ),
  41718. Math.floor( height )
  41719. );
  41720. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  41721. draw();
  41722. }
  41723. }
  41724. } else {
  41725. draw();
  41726. }
  41727. //
  41728. gl.bindVertexArray( null );
  41729. }
  41730. /**
  41731. * Explain why always null is returned.
  41732. *
  41733. * @param {RenderObject} renderObject - The render object.
  41734. * @return {Boolean} Whether the render pipeline requires an update or not.
  41735. */
  41736. needsRenderUpdate( /*renderObject*/ ) {
  41737. return false;
  41738. }
  41739. /**
  41740. * Explain why no cache key is computed.
  41741. *
  41742. * @param {RenderObject} renderObject - The render object.
  41743. * @return {String} The cache key.
  41744. */
  41745. getRenderCacheKey( /*renderObject*/ ) {
  41746. return '';
  41747. }
  41748. // textures
  41749. /**
  41750. * Creates a default texture for the given texture that can be used
  41751. * as a placeholder until the actual texture is ready for usage.
  41752. *
  41753. * @param {Texture} texture - The texture to create a default texture for.
  41754. */
  41755. createDefaultTexture( texture ) {
  41756. this.textureUtils.createDefaultTexture( texture );
  41757. }
  41758. /**
  41759. * Defines a texture on the GPU for the given texture object.
  41760. *
  41761. * @param {Texture} texture - The texture.
  41762. * @param {Object} [options={}] - Optional configuration parameter.
  41763. */
  41764. createTexture( texture, options ) {
  41765. this.textureUtils.createTexture( texture, options );
  41766. }
  41767. /**
  41768. * Uploads the updated texture data to the GPU.
  41769. *
  41770. * @param {Texture} texture - The texture.
  41771. * @param {Object} [options={}] - Optional configuration parameter.
  41772. */
  41773. updateTexture( texture, options ) {
  41774. this.textureUtils.updateTexture( texture, options );
  41775. }
  41776. /**
  41777. * Generates mipmaps for the given texture.
  41778. *
  41779. * @param {Texture} texture - The texture.
  41780. */
  41781. generateMipmaps( texture ) {
  41782. this.textureUtils.generateMipmaps( texture );
  41783. }
  41784. /**
  41785. * Destroys the GPU data for the given texture object.
  41786. *
  41787. * @param {Texture} texture - The texture.
  41788. */
  41789. destroyTexture( texture ) {
  41790. this.textureUtils.destroyTexture( texture );
  41791. }
  41792. /**
  41793. * Returns texture data as a typed array.
  41794. *
  41795. * @async
  41796. * @param {Texture} texture - The texture to copy.
  41797. * @param {Number} x - The x coordinate of the copy origin.
  41798. * @param {Number} y - The y coordinate of the copy origin.
  41799. * @param {Number} width - The width of the copy.
  41800. * @param {Number} height - The height of the copy.
  41801. * @param {Number} faceIndex - The face index.
  41802. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41803. */
  41804. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41805. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  41806. }
  41807. /**
  41808. * This method does nothing since WebGL 2 has no concept of samplers.
  41809. *
  41810. * @param {Texture} texture - The texture to create the sampler for.
  41811. */
  41812. createSampler( /*texture*/ ) {
  41813. //console.warn( 'Abstract class.' );
  41814. }
  41815. /**
  41816. * This method does nothing since WebGL 2 has no concept of samplers.
  41817. *
  41818. * @param {Texture} texture - The texture to destroy the sampler for.
  41819. */
  41820. destroySampler( /*texture*/ ) {}
  41821. // node builder
  41822. /**
  41823. * Returns a node builder for the given render object.
  41824. *
  41825. * @param {RenderObject} object - The render object.
  41826. * @param {Renderer} renderer - The renderer.
  41827. * @return {GLSLNodeBuilder} The node builder.
  41828. */
  41829. createNodeBuilder( object, renderer ) {
  41830. return new GLSLNodeBuilder( object, renderer );
  41831. }
  41832. // program
  41833. /**
  41834. * Creates a shader program from the given programmable stage.
  41835. *
  41836. * @param {ProgrammableStage} program - The programmable stage.
  41837. */
  41838. createProgram( program ) {
  41839. const gl = this.gl;
  41840. const { stage, code } = program;
  41841. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41842. gl.shaderSource( shader, code );
  41843. gl.compileShader( shader );
  41844. this.set( program, {
  41845. shaderGPU: shader
  41846. } );
  41847. }
  41848. /**
  41849. * Destroys the shader program of the given programmable stage.
  41850. *
  41851. * @param {ProgrammableStage} program - The programmable stage.
  41852. */
  41853. destroyProgram( program ) {
  41854. this.delete( program );
  41855. }
  41856. /**
  41857. * Creates a render pipeline for the given render object.
  41858. *
  41859. * @param {RenderObject} renderObject - The render object.
  41860. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  41861. */
  41862. createRenderPipeline( renderObject, promises ) {
  41863. const gl = this.gl;
  41864. const pipeline = renderObject.pipeline;
  41865. // Program
  41866. const { fragmentProgram, vertexProgram } = pipeline;
  41867. const programGPU = gl.createProgram();
  41868. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41869. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41870. gl.attachShader( programGPU, fragmentShader );
  41871. gl.attachShader( programGPU, vertexShader );
  41872. gl.linkProgram( programGPU );
  41873. this.set( pipeline, {
  41874. programGPU,
  41875. fragmentShader,
  41876. vertexShader
  41877. } );
  41878. if ( promises !== null && this.parallel ) {
  41879. const p = new Promise( ( resolve /*, reject*/ ) => {
  41880. const parallel = this.parallel;
  41881. const checkStatus = () => {
  41882. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41883. this._completeCompile( renderObject, pipeline );
  41884. resolve();
  41885. } else {
  41886. requestAnimationFrame( checkStatus );
  41887. }
  41888. };
  41889. checkStatus();
  41890. } );
  41891. promises.push( p );
  41892. return;
  41893. }
  41894. this._completeCompile( renderObject, pipeline );
  41895. }
  41896. /**
  41897. * Formats the source code of error messages.
  41898. *
  41899. * @private
  41900. * @param {String} string - The code.
  41901. * @param {Number} errorLine - The error line.
  41902. * @return {String} The formatted code.
  41903. */
  41904. _handleSource( string, errorLine ) {
  41905. const lines = string.split( '\n' );
  41906. const lines2 = [];
  41907. const from = Math.max( errorLine - 6, 0 );
  41908. const to = Math.min( errorLine + 6, lines.length );
  41909. for ( let i = from; i < to; i ++ ) {
  41910. const line = i + 1;
  41911. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41912. }
  41913. return lines2.join( '\n' );
  41914. }
  41915. /**
  41916. * Gets the shader compilation errors from the info log.
  41917. *
  41918. * @private
  41919. * @param {WebGL2RenderingContext} gl - The rendering context.
  41920. * @param {WebGLShader} shader - The WebGL shader object.
  41921. * @param {String} type - The shader type.
  41922. * @return {String} The shader errors.
  41923. */
  41924. _getShaderErrors( gl, shader, type ) {
  41925. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41926. const errors = gl.getShaderInfoLog( shader ).trim();
  41927. if ( status && errors === '' ) return '';
  41928. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41929. if ( errorMatches ) {
  41930. const errorLine = parseInt( errorMatches[ 1 ] );
  41931. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41932. } else {
  41933. return errors;
  41934. }
  41935. }
  41936. /**
  41937. * Logs shader compilation errors.
  41938. *
  41939. * @private
  41940. * @param {WebGLProgram} programGPU - The WebGL program.
  41941. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  41942. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  41943. */
  41944. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41945. if ( this.renderer.debug.checkShaderErrors ) {
  41946. const gl = this.gl;
  41947. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41948. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41949. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41950. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41951. } else {
  41952. // default error reporting
  41953. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41954. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41955. console.error(
  41956. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41957. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41958. 'Program Info Log: ' + programLog + '\n' +
  41959. vertexErrors + '\n' +
  41960. fragmentErrors
  41961. );
  41962. }
  41963. } else if ( programLog !== '' ) {
  41964. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41965. }
  41966. }
  41967. }
  41968. /**
  41969. * Completes the shader program setup for the given render object.
  41970. *
  41971. * @private
  41972. * @param {RenderObject} renderObject - The render object.
  41973. * @param {RenderPipeline} pipeline - The render pipeline.
  41974. */
  41975. _completeCompile( renderObject, pipeline ) {
  41976. const { state, gl } = this;
  41977. const pipelineData = this.get( pipeline );
  41978. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41979. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41980. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41981. }
  41982. state.useProgram( programGPU );
  41983. // Bindings
  41984. const bindings = renderObject.getBindings();
  41985. this._setupBindings( bindings, programGPU );
  41986. //
  41987. this.set( pipeline, {
  41988. programGPU
  41989. } );
  41990. }
  41991. /**
  41992. * Creates a compute pipeline for the given compute node.
  41993. *
  41994. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41995. * @param {Array<BindGroup>} bindings - The bindings.
  41996. */
  41997. createComputePipeline( computePipeline, bindings ) {
  41998. const { state, gl } = this;
  41999. // Program
  42000. const fragmentProgram = {
  42001. stage: 'fragment',
  42002. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  42003. };
  42004. this.createProgram( fragmentProgram );
  42005. const { computeProgram } = computePipeline;
  42006. const programGPU = gl.createProgram();
  42007. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42008. const vertexShader = this.get( computeProgram ).shaderGPU;
  42009. const transforms = computeProgram.transforms;
  42010. const transformVaryingNames = [];
  42011. const transformAttributeNodes = [];
  42012. for ( let i = 0; i < transforms.length; i ++ ) {
  42013. const transform = transforms[ i ];
  42014. transformVaryingNames.push( transform.varyingName );
  42015. transformAttributeNodes.push( transform.attributeNode );
  42016. }
  42017. gl.attachShader( programGPU, fragmentShader );
  42018. gl.attachShader( programGPU, vertexShader );
  42019. gl.transformFeedbackVaryings(
  42020. programGPU,
  42021. transformVaryingNames,
  42022. gl.SEPARATE_ATTRIBS
  42023. );
  42024. gl.linkProgram( programGPU );
  42025. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  42026. this._logProgramError( programGPU, fragmentShader, vertexShader );
  42027. }
  42028. state.useProgram( programGPU );
  42029. // Bindings
  42030. this._setupBindings( bindings, programGPU );
  42031. const attributeNodes = computeProgram.attributes;
  42032. const attributes = [];
  42033. const transformBuffers = [];
  42034. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  42035. const attribute = attributeNodes[ i ].node.attribute;
  42036. attributes.push( attribute );
  42037. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42038. }
  42039. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  42040. const attribute = transformAttributeNodes[ i ].attribute;
  42041. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42042. const attributeData = this.get( attribute );
  42043. transformBuffers.push( attributeData );
  42044. }
  42045. //
  42046. this.set( computePipeline, {
  42047. programGPU,
  42048. transformBuffers,
  42049. attributes
  42050. } );
  42051. }
  42052. /**
  42053. * Creates bindings from the given bind group definition.
  42054. *
  42055. * @param {BindGroup} bindGroup - The bind group.
  42056. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42057. * @param {Number} cacheIndex - The cache index.
  42058. * @param {Number} version - The version.
  42059. */
  42060. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  42061. if ( this._knownBindings.has( bindings ) === false ) {
  42062. this._knownBindings.add( bindings );
  42063. let uniformBuffers = 0;
  42064. let textures = 0;
  42065. for ( const bindGroup of bindings ) {
  42066. this.set( bindGroup, {
  42067. textures: textures,
  42068. uniformBuffers: uniformBuffers
  42069. } );
  42070. for ( const binding of bindGroup.bindings ) {
  42071. if ( binding.isUniformBuffer ) uniformBuffers ++;
  42072. if ( binding.isSampledTexture ) textures ++;
  42073. }
  42074. }
  42075. }
  42076. this.updateBindings( bindGroup, bindings );
  42077. }
  42078. /**
  42079. * Updates the given bind group definition.
  42080. *
  42081. * @param {BindGroup} bindGroup - The bind group.
  42082. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42083. * @param {Number} cacheIndex - The cache index.
  42084. * @param {Number} version - The version.
  42085. */
  42086. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  42087. const { gl } = this;
  42088. const bindGroupData = this.get( bindGroup );
  42089. let i = bindGroupData.uniformBuffers;
  42090. let t = bindGroupData.textures;
  42091. for ( const binding of bindGroup.bindings ) {
  42092. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42093. const data = binding.buffer;
  42094. const bufferGPU = gl.createBuffer();
  42095. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42096. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42097. this.set( binding, {
  42098. index: i ++,
  42099. bufferGPU
  42100. } );
  42101. } else if ( binding.isSampledTexture ) {
  42102. const { textureGPU, glTextureType } = this.get( binding.texture );
  42103. this.set( binding, {
  42104. index: t ++,
  42105. textureGPU,
  42106. glTextureType
  42107. } );
  42108. }
  42109. }
  42110. }
  42111. /**
  42112. * Updates a buffer binding.
  42113. *
  42114. * @param {Buffer} binding - The buffer binding to update.
  42115. */
  42116. updateBinding( binding ) {
  42117. const gl = this.gl;
  42118. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42119. const bindingData = this.get( binding );
  42120. const bufferGPU = bindingData.bufferGPU;
  42121. const data = binding.buffer;
  42122. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42123. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  42124. }
  42125. }
  42126. // attributes
  42127. /**
  42128. * Creates the GPU buffer of an indexed shader attribute.
  42129. *
  42130. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  42131. */
  42132. createIndexAttribute( attribute ) {
  42133. const gl = this.gl;
  42134. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  42135. }
  42136. /**
  42137. * Creates the GPU buffer of a shader attribute.
  42138. *
  42139. * @param {BufferAttribute} attribute - The buffer attribute.
  42140. */
  42141. createAttribute( attribute ) {
  42142. if ( this.has( attribute ) ) return;
  42143. const gl = this.gl;
  42144. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42145. }
  42146. /**
  42147. * Creates the GPU buffer of a storage attribute.
  42148. *
  42149. * @param {BufferAttribute} attribute - The buffer attribute.
  42150. */
  42151. createStorageAttribute( attribute ) {
  42152. if ( this.has( attribute ) ) return;
  42153. const gl = this.gl;
  42154. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  42155. }
  42156. /**
  42157. * Updates the GPU buffer of a shader attribute.
  42158. *
  42159. * @param {BufferAttribute} attribute - The buffer attribute to update.
  42160. */
  42161. updateAttribute( attribute ) {
  42162. this.attributeUtils.updateAttribute( attribute );
  42163. }
  42164. /**
  42165. * Destroys the GPU buffer of a shader attribute.
  42166. *
  42167. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  42168. */
  42169. destroyAttribute( attribute ) {
  42170. this.attributeUtils.destroyAttribute( attribute );
  42171. }
  42172. /**
  42173. * Checks if the given feature is supported by the backend.
  42174. *
  42175. * @param {String} name - The feature's name.
  42176. * @return {Boolean} Whether the feature is supported or not.
  42177. */
  42178. hasFeature( name ) {
  42179. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  42180. const extensions = this.extensions;
  42181. for ( let i = 0; i < keysMatching.length; i ++ ) {
  42182. if ( extensions.has( keysMatching[ i ] ) ) return true;
  42183. }
  42184. return false;
  42185. }
  42186. /**
  42187. * Returns the maximum anisotropy texture filtering value.
  42188. *
  42189. * @return {Number} The maximum anisotropy texture filtering value.
  42190. */
  42191. getMaxAnisotropy() {
  42192. return this.capabilities.getMaxAnisotropy();
  42193. }
  42194. /**
  42195. * Copies data of the given source texture to the given destination texture.
  42196. *
  42197. * @param {Texture} srcTexture - The source texture.
  42198. * @param {Texture} dstTexture - The destination texture.
  42199. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  42200. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  42201. * @param {Number} [level=0] - The mip level to copy.
  42202. */
  42203. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  42204. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  42205. }
  42206. /**
  42207. * Copies the current bound framebuffer to the given texture.
  42208. *
  42209. * @param {Texture} texture - The destination texture.
  42210. * @param {RenderContext} renderContext - The render context.
  42211. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42212. */
  42213. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42214. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  42215. }
  42216. /**
  42217. * Configures the active framebuffer from the given render context.
  42218. *
  42219. * @private
  42220. * @param {RenderContext} descriptor - The render context.
  42221. */
  42222. _setFramebuffer( descriptor ) {
  42223. const { gl, state } = this;
  42224. let currentFrameBuffer = null;
  42225. if ( descriptor.textures !== null ) {
  42226. const renderTarget = descriptor.renderTarget;
  42227. const renderTargetContextData = this.get( renderTarget );
  42228. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  42229. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  42230. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  42231. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  42232. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  42233. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  42234. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  42235. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  42236. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42237. const useMultisampledRTT = this._useMultisampledRTT( renderTarget );
  42238. const cacheKey = getCacheKey( descriptor );
  42239. let fb;
  42240. if ( isCube ) {
  42241. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  42242. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  42243. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  42244. fb = this._xrFamebuffer;
  42245. } else {
  42246. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  42247. fb = renderTargetContextData.framebuffers[ cacheKey ];
  42248. }
  42249. if ( fb === undefined ) {
  42250. fb = gl.createFramebuffer();
  42251. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  42252. const textures = descriptor.textures;
  42253. if ( isCube ) {
  42254. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  42255. const { textureGPU } = this.get( textures[ 0 ] );
  42256. const cubeFace = this.renderer._activeCubeFace;
  42257. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  42258. } else {
  42259. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  42260. for ( let i = 0; i < textures.length; i ++ ) {
  42261. const texture = textures[ i ];
  42262. const textureData = this.get( texture );
  42263. textureData.renderTarget = descriptor.renderTarget;
  42264. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  42265. const attachment = gl.COLOR_ATTACHMENT0 + i;
  42266. if ( isRenderTarget3D || isRenderTargetArray ) {
  42267. const layer = this.renderer._activeCubeFace;
  42268. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  42269. } else {
  42270. if ( useMultisampledRTT ) {
  42271. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42272. } else {
  42273. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42274. }
  42275. }
  42276. }
  42277. state.drawBuffers( descriptor, fb );
  42278. }
  42279. if ( renderTarget.isXRRenderTarget && renderTarget.autoAllocateDepthBuffer === true ) {
  42280. const renderbuffer = gl.createRenderbuffer();
  42281. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  42282. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  42283. } else {
  42284. if ( descriptor.depthTexture !== null ) {
  42285. const textureData = this.get( descriptor.depthTexture );
  42286. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42287. textureData.renderTarget = descriptor.renderTarget;
  42288. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  42289. if ( useMultisampledRTT ) {
  42290. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42291. } else {
  42292. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42293. }
  42294. }
  42295. }
  42296. } else {
  42297. // rebind external XR textures
  42298. if ( isXRRenderTarget && hasExternalTextures ) {
  42299. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  42300. // rebind color
  42301. const textureData = this.get( descriptor.textures[ 0 ] );
  42302. if ( useMultisampledRTT ) {
  42303. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42304. } else {
  42305. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42306. }
  42307. // rebind depth
  42308. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42309. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  42310. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  42311. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  42312. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  42313. } else {
  42314. const textureData = this.get( descriptor.depthTexture );
  42315. if ( useMultisampledRTT ) {
  42316. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  42317. } else {
  42318. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  42319. }
  42320. }
  42321. }
  42322. }
  42323. if ( samples > 0 && useMultisampledRTT === false ) {
  42324. if ( msaaFb === undefined ) {
  42325. const invalidationArray = [];
  42326. msaaFb = gl.createFramebuffer();
  42327. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  42328. const msaaRenderbuffers = [];
  42329. const textures = descriptor.textures;
  42330. for ( let i = 0; i < textures.length; i ++ ) {
  42331. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  42332. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42333. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  42334. if ( depthBuffer ) {
  42335. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42336. invalidationArray.push( depthStyle );
  42337. }
  42338. const texture = descriptor.textures[ i ];
  42339. const textureData = this.get( texture );
  42340. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  42341. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  42342. }
  42343. renderTargetContextData.msaaFrameBuffer = msaaFb;
  42344. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  42345. if ( depthRenderbuffer === undefined ) {
  42346. depthRenderbuffer = gl.createRenderbuffer();
  42347. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  42348. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  42349. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  42350. invalidationArray.push( depthStyle );
  42351. }
  42352. renderTargetContextData.invalidationArray = invalidationArray;
  42353. }
  42354. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42355. } else {
  42356. currentFrameBuffer = fb;
  42357. }
  42358. }
  42359. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  42360. }
  42361. /**
  42362. * Computes the VAO key for the given index and attributes.
  42363. *
  42364. * @private
  42365. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  42366. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42367. * @return {String} The VAO key.
  42368. */
  42369. _getVaoKey( index, attributes ) {
  42370. let key = '';
  42371. if ( index !== null ) {
  42372. const indexData = this.get( index );
  42373. key += ':' + indexData.id;
  42374. }
  42375. for ( let i = 0; i < attributes.length; i ++ ) {
  42376. const attributeData = this.get( attributes[ i ] );
  42377. key += ':' + attributeData.id;
  42378. }
  42379. return key;
  42380. }
  42381. /**
  42382. * Creates a VAO from the index and attributes.
  42383. *
  42384. * @private
  42385. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  42386. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  42387. * @return {Object} The VAO data.
  42388. */
  42389. _createVao( index, attributes ) {
  42390. const { gl } = this;
  42391. const vaoGPU = gl.createVertexArray();
  42392. let key = '';
  42393. let staticVao = true;
  42394. gl.bindVertexArray( vaoGPU );
  42395. if ( index !== null ) {
  42396. const indexData = this.get( index );
  42397. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  42398. key += ':' + indexData.id;
  42399. }
  42400. for ( let i = 0; i < attributes.length; i ++ ) {
  42401. const attribute = attributes[ i ];
  42402. const attributeData = this.get( attribute );
  42403. key += ':' + attributeData.id;
  42404. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  42405. gl.enableVertexAttribArray( i );
  42406. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  42407. let stride, offset;
  42408. if ( attribute.isInterleavedBufferAttribute === true ) {
  42409. stride = attribute.data.stride * attributeData.bytesPerElement;
  42410. offset = attribute.offset * attributeData.bytesPerElement;
  42411. } else {
  42412. stride = 0;
  42413. offset = 0;
  42414. }
  42415. if ( attributeData.isInteger ) {
  42416. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  42417. } else {
  42418. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  42419. }
  42420. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  42421. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  42422. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  42423. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  42424. }
  42425. }
  42426. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  42427. this.vaoCache[ key ] = vaoGPU;
  42428. return { vaoGPU, staticVao };
  42429. }
  42430. /**
  42431. * Creates a transform feedback from the given transform buffers.
  42432. *
  42433. * @private
  42434. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  42435. * @return {WebGLTransformFeedback} The transform feedback.
  42436. */
  42437. _getTransformFeedback( transformBuffers ) {
  42438. let key = '';
  42439. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42440. key += ':' + transformBuffers[ i ].id;
  42441. }
  42442. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  42443. if ( transformFeedbackGPU !== undefined ) {
  42444. return transformFeedbackGPU;
  42445. }
  42446. const { gl } = this;
  42447. transformFeedbackGPU = gl.createTransformFeedback();
  42448. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42449. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42450. const attributeData = transformBuffers[ i ];
  42451. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  42452. }
  42453. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42454. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  42455. return transformFeedbackGPU;
  42456. }
  42457. /**
  42458. * Setups the given bindings.
  42459. *
  42460. * @private
  42461. * @param {Array<BindGroup>} bindings - The bindings.
  42462. * @param {WebGLProgram} programGPU - The WebGL program.
  42463. */
  42464. _setupBindings( bindings, programGPU ) {
  42465. const gl = this.gl;
  42466. for ( const bindGroup of bindings ) {
  42467. for ( const binding of bindGroup.bindings ) {
  42468. const bindingData = this.get( binding );
  42469. const index = bindingData.index;
  42470. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42471. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  42472. gl.uniformBlockBinding( programGPU, location, index );
  42473. } else if ( binding.isSampledTexture ) {
  42474. const location = gl.getUniformLocation( programGPU, binding.name );
  42475. gl.uniform1i( location, index );
  42476. }
  42477. }
  42478. }
  42479. }
  42480. /**
  42481. * Binds the given uniforms.
  42482. *
  42483. * @private
  42484. * @param {Array<BindGroup>} bindings - The bindings.
  42485. */
  42486. _bindUniforms( bindings ) {
  42487. const { gl, state } = this;
  42488. for ( const bindGroup of bindings ) {
  42489. for ( const binding of bindGroup.bindings ) {
  42490. const bindingData = this.get( binding );
  42491. const index = bindingData.index;
  42492. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  42493. // TODO USE bindBufferRange to group multiple uniform buffers
  42494. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  42495. } else if ( binding.isSampledTexture ) {
  42496. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  42497. }
  42498. }
  42499. }
  42500. }
  42501. /**
  42502. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  42503. * should be used when MSAA is enabled.
  42504. *
  42505. * @private
  42506. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  42507. * @return {Boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  42508. */
  42509. _useMultisampledRTT( renderTarget ) {
  42510. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget.autoAllocateDepthBuffer !== false;
  42511. }
  42512. /**
  42513. * Frees internal resources.
  42514. */
  42515. dispose() {
  42516. const extension = this.extensions.get( 'WEBGL_lose_context' );
  42517. if ( extension ) extension.loseContext();
  42518. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  42519. }
  42520. }
  42521. const GPUPrimitiveTopology = {
  42522. PointList: 'point-list',
  42523. LineList: 'line-list',
  42524. LineStrip: 'line-strip',
  42525. TriangleList: 'triangle-list',
  42526. TriangleStrip: 'triangle-strip',
  42527. };
  42528. const GPUCompareFunction = {
  42529. Never: 'never',
  42530. Less: 'less',
  42531. Equal: 'equal',
  42532. LessEqual: 'less-equal',
  42533. Greater: 'greater',
  42534. NotEqual: 'not-equal',
  42535. GreaterEqual: 'greater-equal',
  42536. Always: 'always'
  42537. };
  42538. const GPUStoreOp = {
  42539. Store: 'store',
  42540. Discard: 'discard'
  42541. };
  42542. const GPULoadOp = {
  42543. Load: 'load',
  42544. Clear: 'clear'
  42545. };
  42546. const GPUFrontFace = {
  42547. CCW: 'ccw',
  42548. CW: 'cw'
  42549. };
  42550. const GPUCullMode = {
  42551. None: 'none',
  42552. Front: 'front',
  42553. Back: 'back'
  42554. };
  42555. const GPUIndexFormat = {
  42556. Uint16: 'uint16',
  42557. Uint32: 'uint32'
  42558. };
  42559. const GPUTextureFormat = {
  42560. // 8-bit formats
  42561. R8Unorm: 'r8unorm',
  42562. R8Snorm: 'r8snorm',
  42563. R8Uint: 'r8uint',
  42564. R8Sint: 'r8sint',
  42565. // 16-bit formats
  42566. R16Uint: 'r16uint',
  42567. R16Sint: 'r16sint',
  42568. R16Float: 'r16float',
  42569. RG8Unorm: 'rg8unorm',
  42570. RG8Snorm: 'rg8snorm',
  42571. RG8Uint: 'rg8uint',
  42572. RG8Sint: 'rg8sint',
  42573. // 32-bit formats
  42574. R32Uint: 'r32uint',
  42575. R32Sint: 'r32sint',
  42576. R32Float: 'r32float',
  42577. RG16Uint: 'rg16uint',
  42578. RG16Sint: 'rg16sint',
  42579. RG16Float: 'rg16float',
  42580. RGBA8Unorm: 'rgba8unorm',
  42581. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  42582. RGBA8Snorm: 'rgba8snorm',
  42583. RGBA8Uint: 'rgba8uint',
  42584. RGBA8Sint: 'rgba8sint',
  42585. BGRA8Unorm: 'bgra8unorm',
  42586. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  42587. // Packed 32-bit formats
  42588. RGB9E5UFloat: 'rgb9e5ufloat',
  42589. RGB10A2Unorm: 'rgb10a2unorm',
  42590. RG11B10uFloat: 'rgb10a2unorm',
  42591. // 64-bit formats
  42592. RG32Uint: 'rg32uint',
  42593. RG32Sint: 'rg32sint',
  42594. RG32Float: 'rg32float',
  42595. RGBA16Uint: 'rgba16uint',
  42596. RGBA16Sint: 'rgba16sint',
  42597. RGBA16Float: 'rgba16float',
  42598. // 128-bit formats
  42599. RGBA32Uint: 'rgba32uint',
  42600. RGBA32Sint: 'rgba32sint',
  42601. RGBA32Float: 'rgba32float',
  42602. // Depth and stencil formats
  42603. Stencil8: 'stencil8',
  42604. Depth16Unorm: 'depth16unorm',
  42605. Depth24Plus: 'depth24plus',
  42606. Depth24PlusStencil8: 'depth24plus-stencil8',
  42607. Depth32Float: 'depth32float',
  42608. // 'depth32float-stencil8' extension
  42609. Depth32FloatStencil8: 'depth32float-stencil8',
  42610. // BC compressed formats usable if 'texture-compression-bc' is both
  42611. // supported by the device/user agent and enabled in requestDevice.
  42612. BC1RGBAUnorm: 'bc1-rgba-unorm',
  42613. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  42614. BC2RGBAUnorm: 'bc2-rgba-unorm',
  42615. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  42616. BC3RGBAUnorm: 'bc3-rgba-unorm',
  42617. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  42618. BC4RUnorm: 'bc4-r-unorm',
  42619. BC4RSnorm: 'bc4-r-snorm',
  42620. BC5RGUnorm: 'bc5-rg-unorm',
  42621. BC5RGSnorm: 'bc5-rg-snorm',
  42622. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  42623. BC6HRGBFloat: 'bc6h-rgb-float',
  42624. BC7RGBAUnorm: 'bc7-rgba-unorm',
  42625. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  42626. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  42627. // supported by the device/user agent and enabled in requestDevice.
  42628. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  42629. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  42630. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  42631. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  42632. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  42633. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  42634. EACR11Unorm: 'eac-r11unorm',
  42635. EACR11Snorm: 'eac-r11snorm',
  42636. EACRG11Unorm: 'eac-rg11unorm',
  42637. EACRG11Snorm: 'eac-rg11snorm',
  42638. // ASTC compressed formats usable if 'texture-compression-astc' is both
  42639. // supported by the device/user agent and enabled in requestDevice.
  42640. ASTC4x4Unorm: 'astc-4x4-unorm',
  42641. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  42642. ASTC5x4Unorm: 'astc-5x4-unorm',
  42643. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  42644. ASTC5x5Unorm: 'astc-5x5-unorm',
  42645. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  42646. ASTC6x5Unorm: 'astc-6x5-unorm',
  42647. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  42648. ASTC6x6Unorm: 'astc-6x6-unorm',
  42649. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  42650. ASTC8x5Unorm: 'astc-8x5-unorm',
  42651. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  42652. ASTC8x6Unorm: 'astc-8x6-unorm',
  42653. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  42654. ASTC8x8Unorm: 'astc-8x8-unorm',
  42655. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  42656. ASTC10x5Unorm: 'astc-10x5-unorm',
  42657. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  42658. ASTC10x6Unorm: 'astc-10x6-unorm',
  42659. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  42660. ASTC10x8Unorm: 'astc-10x8-unorm',
  42661. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  42662. ASTC10x10Unorm: 'astc-10x10-unorm',
  42663. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  42664. ASTC12x10Unorm: 'astc-12x10-unorm',
  42665. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  42666. ASTC12x12Unorm: 'astc-12x12-unorm',
  42667. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  42668. };
  42669. const GPUAddressMode = {
  42670. ClampToEdge: 'clamp-to-edge',
  42671. Repeat: 'repeat',
  42672. MirrorRepeat: 'mirror-repeat'
  42673. };
  42674. const GPUFilterMode = {
  42675. Linear: 'linear',
  42676. Nearest: 'nearest'
  42677. };
  42678. const GPUBlendFactor = {
  42679. Zero: 'zero',
  42680. One: 'one',
  42681. Src: 'src',
  42682. OneMinusSrc: 'one-minus-src',
  42683. SrcAlpha: 'src-alpha',
  42684. OneMinusSrcAlpha: 'one-minus-src-alpha',
  42685. Dst: 'dst',
  42686. OneMinusDstColor: 'one-minus-dst',
  42687. DstAlpha: 'dst-alpha',
  42688. OneMinusDstAlpha: 'one-minus-dst-alpha',
  42689. SrcAlphaSaturated: 'src-alpha-saturated',
  42690. Constant: 'constant',
  42691. OneMinusConstant: 'one-minus-constant'
  42692. };
  42693. const GPUBlendOperation = {
  42694. Add: 'add',
  42695. Subtract: 'subtract',
  42696. ReverseSubtract: 'reverse-subtract',
  42697. Min: 'min',
  42698. Max: 'max'
  42699. };
  42700. const GPUColorWriteFlags = {
  42701. None: 0,
  42702. Red: 0x1,
  42703. Green: 0x2,
  42704. Blue: 0x4,
  42705. Alpha: 0x8,
  42706. All: 0xF
  42707. };
  42708. const GPUStencilOperation = {
  42709. Keep: 'keep',
  42710. Zero: 'zero',
  42711. Replace: 'replace',
  42712. Invert: 'invert',
  42713. IncrementClamp: 'increment-clamp',
  42714. DecrementClamp: 'decrement-clamp',
  42715. IncrementWrap: 'increment-wrap',
  42716. DecrementWrap: 'decrement-wrap'
  42717. };
  42718. const GPUBufferBindingType = {
  42719. Uniform: 'uniform',
  42720. Storage: 'storage',
  42721. ReadOnlyStorage: 'read-only-storage'
  42722. };
  42723. const GPUStorageTextureAccess = {
  42724. WriteOnly: 'write-only',
  42725. ReadOnly: 'read-only',
  42726. ReadWrite: 'read-write',
  42727. };
  42728. const GPUTextureSampleType = {
  42729. Float: 'float',
  42730. UnfilterableFloat: 'unfilterable-float',
  42731. Depth: 'depth',
  42732. SInt: 'sint',
  42733. UInt: 'uint'
  42734. };
  42735. const GPUTextureDimension = {
  42736. OneD: '1d',
  42737. TwoD: '2d',
  42738. ThreeD: '3d'
  42739. };
  42740. const GPUTextureViewDimension = {
  42741. OneD: '1d',
  42742. TwoD: '2d',
  42743. TwoDArray: '2d-array',
  42744. Cube: 'cube',
  42745. CubeArray: 'cube-array',
  42746. ThreeD: '3d'
  42747. };
  42748. const GPUTextureAspect = {
  42749. All: 'all',
  42750. StencilOnly: 'stencil-only',
  42751. DepthOnly: 'depth-only'
  42752. };
  42753. const GPUInputStepMode = {
  42754. Vertex: 'vertex',
  42755. Instance: 'instance'
  42756. };
  42757. const GPUFeatureName = {
  42758. DepthClipControl: 'depth-clip-control',
  42759. Depth32FloatStencil8: 'depth32float-stencil8',
  42760. TextureCompressionBC: 'texture-compression-bc',
  42761. TextureCompressionETC2: 'texture-compression-etc2',
  42762. TextureCompressionASTC: 'texture-compression-astc',
  42763. TimestampQuery: 'timestamp-query',
  42764. IndirectFirstInstance: 'indirect-first-instance',
  42765. ShaderF16: 'shader-f16',
  42766. RG11B10UFloat: 'rg11b10ufloat-renderable',
  42767. BGRA8UNormStorage: 'bgra8unorm-storage',
  42768. Float32Filterable: 'float32-filterable',
  42769. ClipDistances: 'clip-distances',
  42770. DualSourceBlending: 'dual-source-blending',
  42771. Subgroups: 'subgroups'
  42772. };
  42773. /**
  42774. * Represents a sampler binding type.
  42775. *
  42776. * @private
  42777. * @augments Binding
  42778. */
  42779. class Sampler extends Binding {
  42780. /**
  42781. * Constructs a new sampler.
  42782. *
  42783. * @param {String} name - The samplers's name.
  42784. * @param {Texture?} texture - The texture this binding is referring to.
  42785. */
  42786. constructor( name, texture ) {
  42787. super( name );
  42788. /**
  42789. * The texture the sampler is referring to.
  42790. *
  42791. * @type {Texture?}
  42792. */
  42793. this.texture = texture;
  42794. /**
  42795. * The binding's version.
  42796. *
  42797. * @type {Number}
  42798. */
  42799. this.version = texture ? texture.version : 0;
  42800. /**
  42801. * This flag can be used for type testing.
  42802. *
  42803. * @type {Boolean}
  42804. * @readonly
  42805. * @default true
  42806. */
  42807. this.isSampler = true;
  42808. }
  42809. }
  42810. /**
  42811. * A special form of sampler binding type.
  42812. * It's texture value is managed by a node object.
  42813. *
  42814. * @private
  42815. * @augments Sampler
  42816. */
  42817. class NodeSampler extends Sampler {
  42818. /**
  42819. * Constructs a new node-based sampler.
  42820. *
  42821. * @param {String} name - The samplers's name.
  42822. * @param {TextureNode} textureNode - The texture node.
  42823. * @param {UniformGroupNode} groupNode - The uniform group node.
  42824. */
  42825. constructor( name, textureNode, groupNode ) {
  42826. super( name, textureNode ? textureNode.value : null );
  42827. /**
  42828. * The texture node.
  42829. *
  42830. * @type {TextureNode}
  42831. */
  42832. this.textureNode = textureNode;
  42833. /**
  42834. * The uniform group node.
  42835. *
  42836. * @type {UniformGroupNode}
  42837. */
  42838. this.groupNode = groupNode;
  42839. }
  42840. /**
  42841. * Updates the texture value of this sampler.
  42842. */
  42843. update() {
  42844. this.texture = this.textureNode.value;
  42845. }
  42846. }
  42847. /**
  42848. * Represents a storage buffer binding type.
  42849. *
  42850. * @private
  42851. * @augments Buffer
  42852. */
  42853. class StorageBuffer extends Buffer {
  42854. /**
  42855. * Constructs a new uniform buffer.
  42856. *
  42857. * @param {String} name - The buffer's name.
  42858. * @param {BufferAttribute} attribute - The buffer attribute.
  42859. */
  42860. constructor( name, attribute ) {
  42861. super( name, attribute ? attribute.array : null );
  42862. /**
  42863. * This flag can be used for type testing.
  42864. *
  42865. * @type {BufferAttribute}
  42866. */
  42867. this.attribute = attribute;
  42868. /**
  42869. * This flag can be used for type testing.
  42870. *
  42871. * @type {Boolean}
  42872. * @readonly
  42873. * @default true
  42874. */
  42875. this.isStorageBuffer = true;
  42876. }
  42877. }
  42878. let _id = 0;
  42879. /**
  42880. * A special form of storage buffer binding type.
  42881. * It's buffer value is managed by a node object.
  42882. *
  42883. * @private
  42884. * @augments StorageBuffer
  42885. */
  42886. class NodeStorageBuffer extends StorageBuffer {
  42887. /**
  42888. * Constructs a new node-based storage buffer.
  42889. *
  42890. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  42891. * @param {UniformGroupNode} groupNode - The uniform group node.
  42892. */
  42893. constructor( nodeUniform, groupNode ) {
  42894. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  42895. /**
  42896. * The node uniform.
  42897. *
  42898. * @type {StorageBufferNode}
  42899. */
  42900. this.nodeUniform = nodeUniform;
  42901. /**
  42902. * The access type.
  42903. *
  42904. * @type {String}
  42905. */
  42906. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  42907. /**
  42908. * The uniform group node.
  42909. *
  42910. * @type {UniformGroupNode}
  42911. */
  42912. this.groupNode = groupNode;
  42913. }
  42914. /**
  42915. * The storage buffer.
  42916. *
  42917. * @type {BufferAttribute}
  42918. */
  42919. get buffer() {
  42920. return this.nodeUniform.value;
  42921. }
  42922. }
  42923. /**
  42924. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  42925. *
  42926. * @private
  42927. */
  42928. class WebGPUTexturePassUtils extends DataMap {
  42929. /**
  42930. * Constructs a new utility object.
  42931. *
  42932. * @param {GPUDevice} device - The WebGPU device.
  42933. */
  42934. constructor( device ) {
  42935. super();
  42936. /**
  42937. * The WebGPU device.
  42938. *
  42939. * @type {GPUDevice}
  42940. */
  42941. this.device = device;
  42942. const mipmapVertexSource = `
  42943. struct VarysStruct {
  42944. @builtin( position ) Position: vec4<f32>,
  42945. @location( 0 ) vTex : vec2<f32>
  42946. };
  42947. @vertex
  42948. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  42949. var Varys : VarysStruct;
  42950. var pos = array< vec2<f32>, 4 >(
  42951. vec2<f32>( -1.0, 1.0 ),
  42952. vec2<f32>( 1.0, 1.0 ),
  42953. vec2<f32>( -1.0, -1.0 ),
  42954. vec2<f32>( 1.0, -1.0 )
  42955. );
  42956. var tex = array< vec2<f32>, 4 >(
  42957. vec2<f32>( 0.0, 0.0 ),
  42958. vec2<f32>( 1.0, 0.0 ),
  42959. vec2<f32>( 0.0, 1.0 ),
  42960. vec2<f32>( 1.0, 1.0 )
  42961. );
  42962. Varys.vTex = tex[ vertexIndex ];
  42963. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  42964. return Varys;
  42965. }
  42966. `;
  42967. const mipmapFragmentSource = `
  42968. @group( 0 ) @binding( 0 )
  42969. var imgSampler : sampler;
  42970. @group( 0 ) @binding( 1 )
  42971. var img : texture_2d<f32>;
  42972. @fragment
  42973. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42974. return textureSample( img, imgSampler, vTex );
  42975. }
  42976. `;
  42977. const flipYFragmentSource = `
  42978. @group( 0 ) @binding( 0 )
  42979. var imgSampler : sampler;
  42980. @group( 0 ) @binding( 1 )
  42981. var img : texture_2d<f32>;
  42982. @fragment
  42983. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  42984. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  42985. }
  42986. `;
  42987. /**
  42988. * The mipmap GPU sampler.
  42989. *
  42990. * @type {GPUSampler}
  42991. */
  42992. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  42993. /**
  42994. * The flipY GPU sampler.
  42995. *
  42996. * @type {GPUSampler}
  42997. */
  42998. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  42999. /**
  43000. * A cache for GPU render pipelines used for copy/transfer passes.
  43001. * Every texture format requires a unique pipeline.
  43002. *
  43003. * @type {Object<String,GPURenderPipeline>}
  43004. */
  43005. this.transferPipelines = {};
  43006. /**
  43007. * A cache for GPU render pipelines used for flipY passes.
  43008. * Every texture format requires a unique pipeline.
  43009. *
  43010. * @type {Object<String,GPURenderPipeline>}
  43011. */
  43012. this.flipYPipelines = {};
  43013. /**
  43014. * The mipmap vertex shader module.
  43015. *
  43016. * @type {GPUShaderModule}
  43017. */
  43018. this.mipmapVertexShaderModule = device.createShaderModule( {
  43019. label: 'mipmapVertex',
  43020. code: mipmapVertexSource
  43021. } );
  43022. /**
  43023. * The mipmap fragment shader module.
  43024. *
  43025. * @type {GPUShaderModule}
  43026. */
  43027. this.mipmapFragmentShaderModule = device.createShaderModule( {
  43028. label: 'mipmapFragment',
  43029. code: mipmapFragmentSource
  43030. } );
  43031. /**
  43032. * The flipY fragment shader module.
  43033. *
  43034. * @type {GPUShaderModule}
  43035. */
  43036. this.flipYFragmentShaderModule = device.createShaderModule( {
  43037. label: 'flipYFragment',
  43038. code: flipYFragmentSource
  43039. } );
  43040. }
  43041. /**
  43042. * Returns a render pipeline for the internal copy render pass. The pass
  43043. * requires a unique render pipeline for each texture format.
  43044. *
  43045. * @param {String} format - The GPU texture format
  43046. * @return {GPURenderPipeline} The GPU render pipeline.
  43047. */
  43048. getTransferPipeline( format ) {
  43049. let pipeline = this.transferPipelines[ format ];
  43050. if ( pipeline === undefined ) {
  43051. pipeline = this.device.createRenderPipeline( {
  43052. label: `mipmap-${ format }`,
  43053. vertex: {
  43054. module: this.mipmapVertexShaderModule,
  43055. entryPoint: 'main'
  43056. },
  43057. fragment: {
  43058. module: this.mipmapFragmentShaderModule,
  43059. entryPoint: 'main',
  43060. targets: [ { format } ]
  43061. },
  43062. primitive: {
  43063. topology: GPUPrimitiveTopology.TriangleStrip,
  43064. stripIndexFormat: GPUIndexFormat.Uint32
  43065. },
  43066. layout: 'auto'
  43067. } );
  43068. this.transferPipelines[ format ] = pipeline;
  43069. }
  43070. return pipeline;
  43071. }
  43072. /**
  43073. * Returns a render pipeline for the flipY render pass. The pass
  43074. * requires a unique render pipeline for each texture format.
  43075. *
  43076. * @param {String} format - The GPU texture format
  43077. * @return {GPURenderPipeline} The GPU render pipeline.
  43078. */
  43079. getFlipYPipeline( format ) {
  43080. let pipeline = this.flipYPipelines[ format ];
  43081. if ( pipeline === undefined ) {
  43082. pipeline = this.device.createRenderPipeline( {
  43083. label: `flipY-${ format }`,
  43084. vertex: {
  43085. module: this.mipmapVertexShaderModule,
  43086. entryPoint: 'main'
  43087. },
  43088. fragment: {
  43089. module: this.flipYFragmentShaderModule,
  43090. entryPoint: 'main',
  43091. targets: [ { format } ]
  43092. },
  43093. primitive: {
  43094. topology: GPUPrimitiveTopology.TriangleStrip,
  43095. stripIndexFormat: GPUIndexFormat.Uint32
  43096. },
  43097. layout: 'auto'
  43098. } );
  43099. this.flipYPipelines[ format ] = pipeline;
  43100. }
  43101. return pipeline;
  43102. }
  43103. /**
  43104. * Flip the contents of the given GPU texture along its vertical axis.
  43105. *
  43106. * @param {GPUTexture} textureGPU - The GPU texture object.
  43107. * @param {Object} textureGPUDescriptor - The texture descriptor.
  43108. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  43109. */
  43110. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  43111. const format = textureGPUDescriptor.format;
  43112. const { width, height } = textureGPUDescriptor.size;
  43113. const transferPipeline = this.getTransferPipeline( format );
  43114. const flipYPipeline = this.getFlipYPipeline( format );
  43115. const tempTexture = this.device.createTexture( {
  43116. size: { width, height, depthOrArrayLayers: 1 },
  43117. format,
  43118. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  43119. } );
  43120. const srcView = textureGPU.createView( {
  43121. baseMipLevel: 0,
  43122. mipLevelCount: 1,
  43123. dimension: GPUTextureViewDimension.TwoD,
  43124. baseArrayLayer
  43125. } );
  43126. const dstView = tempTexture.createView( {
  43127. baseMipLevel: 0,
  43128. mipLevelCount: 1,
  43129. dimension: GPUTextureViewDimension.TwoD,
  43130. baseArrayLayer: 0
  43131. } );
  43132. const commandEncoder = this.device.createCommandEncoder( {} );
  43133. const pass = ( pipeline, sourceView, destinationView ) => {
  43134. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  43135. const bindGroup = this.device.createBindGroup( {
  43136. layout: bindGroupLayout,
  43137. entries: [ {
  43138. binding: 0,
  43139. resource: this.flipYSampler
  43140. }, {
  43141. binding: 1,
  43142. resource: sourceView
  43143. } ]
  43144. } );
  43145. const passEncoder = commandEncoder.beginRenderPass( {
  43146. colorAttachments: [ {
  43147. view: destinationView,
  43148. loadOp: GPULoadOp.Clear,
  43149. storeOp: GPUStoreOp.Store,
  43150. clearValue: [ 0, 0, 0, 0 ]
  43151. } ]
  43152. } );
  43153. passEncoder.setPipeline( pipeline );
  43154. passEncoder.setBindGroup( 0, bindGroup );
  43155. passEncoder.draw( 4, 1, 0, 0 );
  43156. passEncoder.end();
  43157. };
  43158. pass( transferPipeline, srcView, dstView );
  43159. pass( flipYPipeline, dstView, srcView );
  43160. this.device.queue.submit( [ commandEncoder.finish() ] );
  43161. tempTexture.destroy();
  43162. }
  43163. /**
  43164. * Generates mipmaps for the given GPU texture.
  43165. *
  43166. * @param {GPUTexture} textureGPU - The GPU texture object.
  43167. * @param {Object} textureGPUDescriptor - The texture descriptor.
  43168. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  43169. */
  43170. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  43171. const textureData = this.get( textureGPU );
  43172. if ( textureData.useCount === undefined ) {
  43173. textureData.useCount = 0;
  43174. textureData.layers = [];
  43175. }
  43176. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  43177. const commandEncoder = this.device.createCommandEncoder( {} );
  43178. this._mipmapRunBundles( commandEncoder, passes );
  43179. this.device.queue.submit( [ commandEncoder.finish() ] );
  43180. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  43181. textureData.useCount ++;
  43182. }
  43183. /**
  43184. * Since multiple copy render passes are required to generate mipmaps, the passes
  43185. * are managed as render bundles to improve performance.
  43186. *
  43187. * @param {GPUTexture} textureGPU - The GPU texture object.
  43188. * @param {Object} textureGPUDescriptor - The texture descriptor.
  43189. * @param {Number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  43190. * @return {Array} An array of render bundles.
  43191. */
  43192. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  43193. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  43194. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  43195. let srcView = textureGPU.createView( {
  43196. baseMipLevel: 0,
  43197. mipLevelCount: 1,
  43198. dimension: GPUTextureViewDimension.TwoD,
  43199. baseArrayLayer
  43200. } );
  43201. const passes = [];
  43202. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  43203. const bindGroup = this.device.createBindGroup( {
  43204. layout: bindGroupLayout,
  43205. entries: [ {
  43206. binding: 0,
  43207. resource: this.mipmapSampler
  43208. }, {
  43209. binding: 1,
  43210. resource: srcView
  43211. } ]
  43212. } );
  43213. const dstView = textureGPU.createView( {
  43214. baseMipLevel: i,
  43215. mipLevelCount: 1,
  43216. dimension: GPUTextureViewDimension.TwoD,
  43217. baseArrayLayer
  43218. } );
  43219. const passDescriptor = {
  43220. colorAttachments: [ {
  43221. view: dstView,
  43222. loadOp: GPULoadOp.Clear,
  43223. storeOp: GPUStoreOp.Store,
  43224. clearValue: [ 0, 0, 0, 0 ]
  43225. } ]
  43226. };
  43227. const passEncoder = this.device.createRenderBundleEncoder( {
  43228. colorFormats: [ textureGPUDescriptor.format ]
  43229. } );
  43230. passEncoder.setPipeline( pipeline );
  43231. passEncoder.setBindGroup( 0, bindGroup );
  43232. passEncoder.draw( 4, 1, 0, 0 );
  43233. passes.push( {
  43234. renderBundles: [ passEncoder.finish() ],
  43235. passDescriptor
  43236. } );
  43237. srcView = dstView;
  43238. }
  43239. return passes;
  43240. }
  43241. /**
  43242. * Executes the render bundles.
  43243. *
  43244. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  43245. * @param {Array} passes - An array of render bundles.
  43246. */
  43247. _mipmapRunBundles( commandEncoder, passes ) {
  43248. const levels = passes.length;
  43249. for ( let i = 0; i < levels; i ++ ) {
  43250. const pass = passes[ i ];
  43251. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  43252. passEncoder.executeBundles( pass.renderBundles );
  43253. passEncoder.end();
  43254. }
  43255. }
  43256. }
  43257. const _compareToWebGPU = {
  43258. [ NeverCompare ]: 'never',
  43259. [ LessCompare ]: 'less',
  43260. [ EqualCompare ]: 'equal',
  43261. [ LessEqualCompare ]: 'less-equal',
  43262. [ GreaterCompare ]: 'greater',
  43263. [ GreaterEqualCompare ]: 'greater-equal',
  43264. [ AlwaysCompare ]: 'always',
  43265. [ NotEqualCompare ]: 'not-equal'
  43266. };
  43267. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  43268. /**
  43269. * A WebGPU backend utility module for managing textures.
  43270. *
  43271. * @private
  43272. */
  43273. class WebGPUTextureUtils {
  43274. /**
  43275. * Constructs a new utility object.
  43276. *
  43277. * @param {WebGPUBackend} backend - The WebGPU backend.
  43278. */
  43279. constructor( backend ) {
  43280. /**
  43281. * A reference to the WebGPU backend.
  43282. *
  43283. * @type {WebGPUBackend}
  43284. */
  43285. this.backend = backend;
  43286. /**
  43287. * A reference to the pass utils.
  43288. *
  43289. * @type {WebGPUTexturePassUtils?}
  43290. * @default null
  43291. */
  43292. this._passUtils = null;
  43293. /**
  43294. * A dictionary for managing default textures. The key
  43295. * is the texture format, the value the texture object.
  43296. *
  43297. * @type {Object<String,Texture>}
  43298. */
  43299. this.defaultTexture = {};
  43300. /**
  43301. * A dictionary for managing default cube textures. The key
  43302. * is the texture format, the value the texture object.
  43303. *
  43304. * @type {Object<String,CubeTexture>}
  43305. */
  43306. this.defaultCubeTexture = {};
  43307. /**
  43308. * A default video frame.
  43309. *
  43310. * @type {VideoFrame?}
  43311. * @default null
  43312. */
  43313. this.defaultVideoFrame = null;
  43314. /**
  43315. * Represents the color attachment of the default framebuffer.
  43316. *
  43317. * @type {GPUTexture?}
  43318. * @default null
  43319. */
  43320. this.colorBuffer = null;
  43321. /**
  43322. * Represents the depth attachment of the default framebuffer.
  43323. *
  43324. * @type {DepthTexture}
  43325. */
  43326. this.depthTexture = new DepthTexture();
  43327. this.depthTexture.name = 'depthBuffer';
  43328. }
  43329. /**
  43330. * Creates a GPU sampler for the given texture.
  43331. *
  43332. * @param {Texture} texture - The texture to create the sampler for.
  43333. */
  43334. createSampler( texture ) {
  43335. const backend = this.backend;
  43336. const device = backend.device;
  43337. const textureGPU = backend.get( texture );
  43338. const samplerDescriptorGPU = {
  43339. addressModeU: this._convertAddressMode( texture.wrapS ),
  43340. addressModeV: this._convertAddressMode( texture.wrapT ),
  43341. addressModeW: this._convertAddressMode( texture.wrapR ),
  43342. magFilter: this._convertFilterMode( texture.magFilter ),
  43343. minFilter: this._convertFilterMode( texture.minFilter ),
  43344. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  43345. maxAnisotropy: 1
  43346. };
  43347. // anisotropy can only be used when all filter modes are set to linear.
  43348. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  43349. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  43350. }
  43351. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  43352. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  43353. }
  43354. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  43355. }
  43356. /**
  43357. * Creates a default texture for the given texture that can be used
  43358. * as a placeholder until the actual texture is ready for usage.
  43359. *
  43360. * @param {Texture} texture - The texture to create a default texture for.
  43361. */
  43362. createDefaultTexture( texture ) {
  43363. let textureGPU;
  43364. const format = getFormat( texture );
  43365. if ( texture.isCubeTexture ) {
  43366. textureGPU = this._getDefaultCubeTextureGPU( format );
  43367. } else if ( texture.isVideoTexture ) {
  43368. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  43369. } else {
  43370. textureGPU = this._getDefaultTextureGPU( format );
  43371. }
  43372. this.backend.get( texture ).texture = textureGPU;
  43373. }
  43374. /**
  43375. * Defines a texture on the GPU for the given texture object.
  43376. *
  43377. * @param {Texture} texture - The texture.
  43378. * @param {Object} [options={}] - Optional configuration parameter.
  43379. * @return {undefined}
  43380. */
  43381. createTexture( texture, options = {} ) {
  43382. const backend = this.backend;
  43383. const textureData = backend.get( texture );
  43384. if ( textureData.initialized ) {
  43385. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  43386. }
  43387. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  43388. if ( options.levels === undefined ) options.levels = 1;
  43389. if ( options.depth === undefined ) options.depth = 1;
  43390. const { width, height, depth, levels } = options;
  43391. if ( texture.isFramebufferTexture ) {
  43392. if ( options.renderTarget ) {
  43393. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  43394. } else {
  43395. options.format = this.backend.utils.getPreferredCanvasFormat();
  43396. }
  43397. }
  43398. const dimension = this._getDimension( texture );
  43399. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  43400. textureData.format = format;
  43401. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  43402. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  43403. if ( texture.isStorageTexture === true ) {
  43404. usage |= GPUTextureUsage.STORAGE_BINDING;
  43405. }
  43406. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  43407. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  43408. }
  43409. const textureDescriptorGPU = {
  43410. label: texture.name,
  43411. size: {
  43412. width: width,
  43413. height: height,
  43414. depthOrArrayLayers: depth,
  43415. },
  43416. mipLevelCount: levels,
  43417. sampleCount: primarySamples,
  43418. dimension: dimension,
  43419. format: format,
  43420. usage: usage
  43421. };
  43422. // texture creation
  43423. if ( texture.isVideoTexture ) {
  43424. const video = texture.source.data;
  43425. const videoFrame = new VideoFrame( video );
  43426. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  43427. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  43428. videoFrame.close();
  43429. textureData.externalTexture = video;
  43430. } else {
  43431. if ( format === undefined ) {
  43432. console.warn( 'WebGPURenderer: Texture format not supported.' );
  43433. return this.createDefaultTexture( texture );
  43434. }
  43435. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  43436. }
  43437. if ( isMSAA ) {
  43438. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  43439. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  43440. msaaTextureDescriptorGPU.sampleCount = samples;
  43441. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  43442. }
  43443. textureData.initialized = true;
  43444. textureData.textureDescriptorGPU = textureDescriptorGPU;
  43445. }
  43446. /**
  43447. * Destroys the GPU data for the given texture object.
  43448. *
  43449. * @param {Texture} texture - The texture.
  43450. */
  43451. destroyTexture( texture ) {
  43452. const backend = this.backend;
  43453. const textureData = backend.get( texture );
  43454. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  43455. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  43456. backend.delete( texture );
  43457. }
  43458. /**
  43459. * Destroys the GPU sampler for the given texture.
  43460. *
  43461. * @param {Texture} texture - The texture to destroy the sampler for.
  43462. */
  43463. destroySampler( texture ) {
  43464. const backend = this.backend;
  43465. const textureData = backend.get( texture );
  43466. delete textureData.sampler;
  43467. }
  43468. /**
  43469. * Generates mipmaps for the given texture.
  43470. *
  43471. * @param {Texture} texture - The texture.
  43472. */
  43473. generateMipmaps( texture ) {
  43474. const textureData = this.backend.get( texture );
  43475. if ( texture.isCubeTexture ) {
  43476. for ( let i = 0; i < 6; i ++ ) {
  43477. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43478. }
  43479. } else {
  43480. const depth = texture.image.depth || 1;
  43481. for ( let i = 0; i < depth; i ++ ) {
  43482. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  43483. }
  43484. }
  43485. }
  43486. /**
  43487. * Returns the color buffer representing the color
  43488. * attachment of the default framebuffer.
  43489. *
  43490. * @return {GPUTexture} The color buffer.
  43491. */
  43492. getColorBuffer() {
  43493. if ( this.colorBuffer ) this.colorBuffer.destroy();
  43494. const backend = this.backend;
  43495. const { width, height } = backend.getDrawingBufferSize();
  43496. this.colorBuffer = backend.device.createTexture( {
  43497. label: 'colorBuffer',
  43498. size: {
  43499. width: width,
  43500. height: height,
  43501. depthOrArrayLayers: 1
  43502. },
  43503. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  43504. format: backend.utils.getPreferredCanvasFormat(),
  43505. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  43506. } );
  43507. return this.colorBuffer;
  43508. }
  43509. /**
  43510. * Returns the depth buffer representing the depth
  43511. * attachment of the default framebuffer.
  43512. *
  43513. * @param {Boolean} [depth=true] - Whether depth is enabled or not.
  43514. * @param {Boolean} [stencil=false] - Whether stencil is enabled or not.
  43515. * @return {GPUTexture} The depth buffer.
  43516. */
  43517. getDepthBuffer( depth = true, stencil = false ) {
  43518. const backend = this.backend;
  43519. const { width, height } = backend.getDrawingBufferSize();
  43520. const depthTexture = this.depthTexture;
  43521. const depthTextureGPU = backend.get( depthTexture ).texture;
  43522. let format, type;
  43523. if ( stencil ) {
  43524. format = DepthStencilFormat;
  43525. type = UnsignedInt248Type;
  43526. } else if ( depth ) {
  43527. format = DepthFormat;
  43528. type = UnsignedIntType;
  43529. }
  43530. if ( depthTextureGPU !== undefined ) {
  43531. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  43532. return depthTextureGPU;
  43533. }
  43534. this.destroyTexture( depthTexture );
  43535. }
  43536. depthTexture.name = 'depthBuffer';
  43537. depthTexture.format = format;
  43538. depthTexture.type = type;
  43539. depthTexture.image.width = width;
  43540. depthTexture.image.height = height;
  43541. this.createTexture( depthTexture, { width, height } );
  43542. return backend.get( depthTexture ).texture;
  43543. }
  43544. /**
  43545. * Uploads the updated texture data to the GPU.
  43546. *
  43547. * @param {Texture} texture - The texture.
  43548. * @param {Object} [options={}] - Optional configuration parameter.
  43549. */
  43550. updateTexture( texture, options ) {
  43551. const textureData = this.backend.get( texture );
  43552. const { textureDescriptorGPU } = textureData;
  43553. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  43554. return;
  43555. // transfer texture data
  43556. if ( texture.isDataTexture ) {
  43557. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43558. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  43559. for ( let i = 0; i < options.image.depth; i ++ ) {
  43560. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  43561. }
  43562. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  43563. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  43564. } else if ( texture.isCubeTexture ) {
  43565. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  43566. } else if ( texture.isVideoTexture ) {
  43567. const video = texture.source.data;
  43568. textureData.externalTexture = video;
  43569. } else {
  43570. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  43571. }
  43572. //
  43573. textureData.version = texture.version;
  43574. if ( texture.onUpdate ) texture.onUpdate( texture );
  43575. }
  43576. /**
  43577. * Returns texture data as a typed array.
  43578. *
  43579. * @async
  43580. * @param {Texture} texture - The texture to copy.
  43581. * @param {Number} x - The x coordinate of the copy origin.
  43582. * @param {Number} y - The y coordinate of the copy origin.
  43583. * @param {Number} width - The width of the copy.
  43584. * @param {Number} height - The height of the copy.
  43585. * @param {Number} faceIndex - The face index.
  43586. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43587. */
  43588. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43589. const device = this.backend.device;
  43590. const textureData = this.backend.get( texture );
  43591. const textureGPU = textureData.texture;
  43592. const format = textureData.textureDescriptorGPU.format;
  43593. const bytesPerTexel = this._getBytesPerTexel( format );
  43594. let bytesPerRow = width * bytesPerTexel;
  43595. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  43596. const readBuffer = device.createBuffer(
  43597. {
  43598. size: width * height * bytesPerTexel,
  43599. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43600. }
  43601. );
  43602. const encoder = device.createCommandEncoder();
  43603. encoder.copyTextureToBuffer(
  43604. {
  43605. texture: textureGPU,
  43606. origin: { x, y, z: faceIndex },
  43607. },
  43608. {
  43609. buffer: readBuffer,
  43610. bytesPerRow: bytesPerRow
  43611. },
  43612. {
  43613. width: width,
  43614. height: height
  43615. }
  43616. );
  43617. const typedArrayType = this._getTypedArrayType( format );
  43618. device.queue.submit( [ encoder.finish() ] );
  43619. await readBuffer.mapAsync( GPUMapMode.READ );
  43620. const buffer = readBuffer.getMappedRange();
  43621. return new typedArrayType( buffer );
  43622. }
  43623. /**
  43624. * Returns `true` if the given texture is an environment map.
  43625. *
  43626. * @private
  43627. * @param {Texture} texture - The texture.
  43628. * @return {Boolean} Whether the given texture is an environment map or not.
  43629. */
  43630. _isEnvironmentTexture( texture ) {
  43631. const mapping = texture.mapping;
  43632. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  43633. }
  43634. /**
  43635. * Returns the default GPU texture for the given format.
  43636. *
  43637. * @private
  43638. * @param {String} format - The GPU format.
  43639. * @return {GPUTexture} The GPU texture.
  43640. */
  43641. _getDefaultTextureGPU( format ) {
  43642. let defaultTexture = this.defaultTexture[ format ];
  43643. if ( defaultTexture === undefined ) {
  43644. const texture = new Texture();
  43645. texture.minFilter = NearestFilter;
  43646. texture.magFilter = NearestFilter;
  43647. this.createTexture( texture, { width: 1, height: 1, format } );
  43648. this.defaultTexture[ format ] = defaultTexture = texture;
  43649. }
  43650. return this.backend.get( defaultTexture ).texture;
  43651. }
  43652. /**
  43653. * Returns the default GPU cube texture for the given format.
  43654. *
  43655. * @private
  43656. * @param {String} format - The GPU format.
  43657. * @return {GPUTexture} The GPU texture.
  43658. */
  43659. _getDefaultCubeTextureGPU( format ) {
  43660. let defaultCubeTexture = this.defaultTexture[ format ];
  43661. if ( defaultCubeTexture === undefined ) {
  43662. const texture = new CubeTexture();
  43663. texture.minFilter = NearestFilter;
  43664. texture.magFilter = NearestFilter;
  43665. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  43666. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  43667. }
  43668. return this.backend.get( defaultCubeTexture ).texture;
  43669. }
  43670. /**
  43671. * Returns the default video frame used as default data in context of video textures.
  43672. *
  43673. * @private
  43674. * @return {VideoFrame} The video frame.
  43675. */
  43676. _getDefaultVideoFrame() {
  43677. let defaultVideoFrame = this.defaultVideoFrame;
  43678. if ( defaultVideoFrame === null ) {
  43679. const init = {
  43680. timestamp: 0,
  43681. codedWidth: 1,
  43682. codedHeight: 1,
  43683. format: 'RGBA',
  43684. };
  43685. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  43686. }
  43687. return defaultVideoFrame;
  43688. }
  43689. /**
  43690. * Uploads cube texture image data to the GPU memory.
  43691. *
  43692. * @private
  43693. * @param {Array} images - The cube image data.
  43694. * @param {GPUTexture} textureGPU - The GPU texture.
  43695. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43696. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  43697. */
  43698. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  43699. for ( let i = 0; i < 6; i ++ ) {
  43700. const image = images[ i ];
  43701. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  43702. if ( image.isDataTexture ) {
  43703. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43704. } else {
  43705. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  43706. }
  43707. }
  43708. }
  43709. /**
  43710. * Uploads texture image data to the GPU memory.
  43711. *
  43712. * @private
  43713. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  43714. * @param {GPUTexture} textureGPU - The GPU texture.
  43715. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43716. * @param {Number} originDepth - The origin depth.
  43717. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  43718. */
  43719. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  43720. const device = this.backend.device;
  43721. device.queue.copyExternalImageToTexture(
  43722. {
  43723. source: image,
  43724. flipY: flipY
  43725. }, {
  43726. texture: textureGPU,
  43727. mipLevel: 0,
  43728. origin: { x: 0, y: 0, z: originDepth }
  43729. }, {
  43730. width: image.width,
  43731. height: image.height,
  43732. depthOrArrayLayers: 1
  43733. }
  43734. );
  43735. }
  43736. /**
  43737. * Returns the pass utils singleton.
  43738. *
  43739. * @private
  43740. * @return {WebGPUTexturePassUtils} The utils instance.
  43741. */
  43742. _getPassUtils() {
  43743. let passUtils = this._passUtils;
  43744. if ( passUtils === null ) {
  43745. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  43746. }
  43747. return passUtils;
  43748. }
  43749. /**
  43750. * Generates mipmaps for the given GPU texture.
  43751. *
  43752. * @private
  43753. * @param {GPUTexture} textureGPU - The GPU texture object.
  43754. * @param {Object} textureDescriptorGPU - The texture descriptor.
  43755. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  43756. */
  43757. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  43758. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  43759. }
  43760. /**
  43761. * Flip the contents of the given GPU texture along its vertical axis.
  43762. *
  43763. * @private
  43764. * @param {GPUTexture} textureGPU - The GPU texture object.
  43765. * @param {Object} textureDescriptorGPU - The texture descriptor.
  43766. * @param {Number} [originDepth=0] - The origin depth.
  43767. */
  43768. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  43769. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  43770. }
  43771. /**
  43772. * Uploads texture buffer data to the GPU memory.
  43773. *
  43774. * @private
  43775. * @param {Object} image - An object defining the image buffer data.
  43776. * @param {GPUTexture} textureGPU - The GPU texture.
  43777. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43778. * @param {Number} originDepth - The origin depth.
  43779. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  43780. * @param {Number} [depth=0] - TODO.
  43781. */
  43782. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  43783. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43784. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  43785. const device = this.backend.device;
  43786. const data = image.data;
  43787. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  43788. const bytesPerRow = image.width * bytesPerTexel;
  43789. device.queue.writeTexture(
  43790. {
  43791. texture: textureGPU,
  43792. mipLevel: 0,
  43793. origin: { x: 0, y: 0, z: originDepth }
  43794. },
  43795. data,
  43796. {
  43797. offset: image.width * image.height * bytesPerTexel * depth,
  43798. bytesPerRow
  43799. },
  43800. {
  43801. width: image.width,
  43802. height: image.height,
  43803. depthOrArrayLayers: 1
  43804. } );
  43805. if ( flipY === true ) {
  43806. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  43807. }
  43808. }
  43809. /**
  43810. * Uploads compressed texture data to the GPU memory.
  43811. *
  43812. * @private
  43813. * @param {Array<Object>} mipmaps - An array with mipmap data.
  43814. * @param {GPUTexture} textureGPU - The GPU texture.
  43815. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  43816. */
  43817. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  43818. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  43819. const device = this.backend.device;
  43820. const blockData = this._getBlockData( textureDescriptorGPU.format );
  43821. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  43822. for ( let i = 0; i < mipmaps.length; i ++ ) {
  43823. const mipmap = mipmaps[ i ];
  43824. const width = mipmap.width;
  43825. const height = mipmap.height;
  43826. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  43827. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  43828. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  43829. for ( let j = 0; j < depth; j ++ ) {
  43830. device.queue.writeTexture(
  43831. {
  43832. texture: textureGPU,
  43833. mipLevel: i,
  43834. origin: { x: 0, y: 0, z: j }
  43835. },
  43836. mipmap.data,
  43837. {
  43838. offset: j * bytesPerImage,
  43839. bytesPerRow,
  43840. rowsPerImage: Math.ceil( height / blockData.height )
  43841. },
  43842. {
  43843. width: Math.ceil( width / blockData.width ) * blockData.width,
  43844. height: Math.ceil( height / blockData.height ) * blockData.height,
  43845. depthOrArrayLayers: 1
  43846. }
  43847. );
  43848. }
  43849. }
  43850. }
  43851. /**
  43852. * This method is only relevant for compressed texture formats. It returns a block
  43853. * data descriptor for the given GPU compressed texture format.
  43854. *
  43855. * @private
  43856. * @param {String} format - The GPU compressed texture format.
  43857. * @return {Object} The block data descriptor.
  43858. */
  43859. _getBlockData( format ) {
  43860. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  43861. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  43862. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  43863. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  43864. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  43865. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  43866. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  43867. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43868. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  43869. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43870. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  43871. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  43872. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  43873. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  43874. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  43875. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  43876. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  43877. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  43878. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  43879. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  43880. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  43881. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  43882. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  43883. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  43884. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  43885. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  43886. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  43887. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  43888. }
  43889. /**
  43890. * Converts the three.js uv wrapping constants to GPU address mode constants.
  43891. *
  43892. * @private
  43893. * @param {Number} value - The three.js constant defining a uv wrapping mode.
  43894. * @return {String} The GPU address mode.
  43895. */
  43896. _convertAddressMode( value ) {
  43897. let addressMode = GPUAddressMode.ClampToEdge;
  43898. if ( value === RepeatWrapping ) {
  43899. addressMode = GPUAddressMode.Repeat;
  43900. } else if ( value === MirroredRepeatWrapping ) {
  43901. addressMode = GPUAddressMode.MirrorRepeat;
  43902. }
  43903. return addressMode;
  43904. }
  43905. /**
  43906. * Converts the three.js filter constants to GPU filter constants.
  43907. *
  43908. * @private
  43909. * @param {Number} value - The three.js constant defining a filter mode.
  43910. * @return {String} The GPU filter mode.
  43911. */
  43912. _convertFilterMode( value ) {
  43913. let filterMode = GPUFilterMode.Linear;
  43914. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  43915. filterMode = GPUFilterMode.Nearest;
  43916. }
  43917. return filterMode;
  43918. }
  43919. /**
  43920. * Returns the bytes-per-texel value for the given GPU texture format.
  43921. *
  43922. * @private
  43923. * @param {String} format - The GPU texture format.
  43924. * @return {Number} The bytes-per-texel.
  43925. */
  43926. _getBytesPerTexel( format ) {
  43927. // 8-bit formats
  43928. if ( format === GPUTextureFormat.R8Unorm ||
  43929. format === GPUTextureFormat.R8Snorm ||
  43930. format === GPUTextureFormat.R8Uint ||
  43931. format === GPUTextureFormat.R8Sint ) return 1;
  43932. // 16-bit formats
  43933. if ( format === GPUTextureFormat.R16Uint ||
  43934. format === GPUTextureFormat.R16Sint ||
  43935. format === GPUTextureFormat.R16Float ||
  43936. format === GPUTextureFormat.RG8Unorm ||
  43937. format === GPUTextureFormat.RG8Snorm ||
  43938. format === GPUTextureFormat.RG8Uint ||
  43939. format === GPUTextureFormat.RG8Sint ) return 2;
  43940. // 32-bit formats
  43941. if ( format === GPUTextureFormat.R32Uint ||
  43942. format === GPUTextureFormat.R32Sint ||
  43943. format === GPUTextureFormat.R32Float ||
  43944. format === GPUTextureFormat.RG16Uint ||
  43945. format === GPUTextureFormat.RG16Sint ||
  43946. format === GPUTextureFormat.RG16Float ||
  43947. format === GPUTextureFormat.RGBA8Unorm ||
  43948. format === GPUTextureFormat.RGBA8UnormSRGB ||
  43949. format === GPUTextureFormat.RGBA8Snorm ||
  43950. format === GPUTextureFormat.RGBA8Uint ||
  43951. format === GPUTextureFormat.RGBA8Sint ||
  43952. format === GPUTextureFormat.BGRA8Unorm ||
  43953. format === GPUTextureFormat.BGRA8UnormSRGB ||
  43954. // Packed 32-bit formats
  43955. format === GPUTextureFormat.RGB9E5UFloat ||
  43956. format === GPUTextureFormat.RGB10A2Unorm ||
  43957. format === GPUTextureFormat.RG11B10UFloat ||
  43958. format === GPUTextureFormat.Depth32Float ||
  43959. format === GPUTextureFormat.Depth24Plus ||
  43960. format === GPUTextureFormat.Depth24PlusStencil8 ||
  43961. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  43962. // 64-bit formats
  43963. if ( format === GPUTextureFormat.RG32Uint ||
  43964. format === GPUTextureFormat.RG32Sint ||
  43965. format === GPUTextureFormat.RG32Float ||
  43966. format === GPUTextureFormat.RGBA16Uint ||
  43967. format === GPUTextureFormat.RGBA16Sint ||
  43968. format === GPUTextureFormat.RGBA16Float ) return 8;
  43969. // 128-bit formats
  43970. if ( format === GPUTextureFormat.RGBA32Uint ||
  43971. format === GPUTextureFormat.RGBA32Sint ||
  43972. format === GPUTextureFormat.RGBA32Float ) return 16;
  43973. }
  43974. /**
  43975. * Returns the corresponding typed array type for the given GPU texture format.
  43976. *
  43977. * @private
  43978. * @param {String} format - The GPU texture format.
  43979. * @return {TypedArray.constructor} The typed array type.
  43980. */
  43981. _getTypedArrayType( format ) {
  43982. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  43983. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  43984. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  43985. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  43986. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  43987. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  43988. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  43989. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  43990. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  43991. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  43992. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  43993. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  43994. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  43995. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  43996. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  43997. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  43998. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  43999. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  44000. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  44001. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  44002. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  44003. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  44004. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  44005. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  44006. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  44007. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  44008. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  44009. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  44010. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  44011. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  44012. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  44013. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  44014. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  44015. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  44016. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  44017. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  44018. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  44019. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  44020. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  44021. }
  44022. /**
  44023. * Returns the GPU dimensions for the given texture.
  44024. *
  44025. * @private
  44026. * @param {Texture} texture - The texture.
  44027. * @return {String} The GPU dimension.
  44028. */
  44029. _getDimension( texture ) {
  44030. let dimension;
  44031. if ( texture.isData3DTexture ) {
  44032. dimension = GPUTextureDimension.ThreeD;
  44033. } else {
  44034. dimension = GPUTextureDimension.TwoD;
  44035. }
  44036. return dimension;
  44037. }
  44038. }
  44039. /**
  44040. * Returns the GPU format for the given texture.
  44041. *
  44042. * @param {Texture} texture - The texture.
  44043. * @param {GPUDevice?} [device=null] - The GPU device which is used for feature detection.
  44044. * It is not necessary to apply the device for most formats.
  44045. * @return {String} The GPU format.
  44046. */
  44047. function getFormat( texture, device = null ) {
  44048. const format = texture.format;
  44049. const type = texture.type;
  44050. const colorSpace = texture.colorSpace;
  44051. let formatGPU;
  44052. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  44053. switch ( format ) {
  44054. case RGBA_S3TC_DXT1_Format:
  44055. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  44056. break;
  44057. case RGBA_S3TC_DXT3_Format:
  44058. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  44059. break;
  44060. case RGBA_S3TC_DXT5_Format:
  44061. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  44062. break;
  44063. case RGB_ETC2_Format:
  44064. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  44065. break;
  44066. case RGBA_ETC2_EAC_Format:
  44067. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  44068. break;
  44069. case RGBA_ASTC_4x4_Format:
  44070. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  44071. break;
  44072. case RGBA_ASTC_5x4_Format:
  44073. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  44074. break;
  44075. case RGBA_ASTC_5x5_Format:
  44076. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  44077. break;
  44078. case RGBA_ASTC_6x5_Format:
  44079. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  44080. break;
  44081. case RGBA_ASTC_6x6_Format:
  44082. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  44083. break;
  44084. case RGBA_ASTC_8x5_Format:
  44085. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  44086. break;
  44087. case RGBA_ASTC_8x6_Format:
  44088. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  44089. break;
  44090. case RGBA_ASTC_8x8_Format:
  44091. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  44092. break;
  44093. case RGBA_ASTC_10x5_Format:
  44094. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  44095. break;
  44096. case RGBA_ASTC_10x6_Format:
  44097. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  44098. break;
  44099. case RGBA_ASTC_10x8_Format:
  44100. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  44101. break;
  44102. case RGBA_ASTC_10x10_Format:
  44103. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  44104. break;
  44105. case RGBA_ASTC_12x10_Format:
  44106. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  44107. break;
  44108. case RGBA_ASTC_12x12_Format:
  44109. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  44110. break;
  44111. case RGBAFormat:
  44112. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  44113. break;
  44114. default:
  44115. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  44116. }
  44117. } else {
  44118. switch ( format ) {
  44119. case RGBAFormat:
  44120. switch ( type ) {
  44121. case ByteType:
  44122. formatGPU = GPUTextureFormat.RGBA8Snorm;
  44123. break;
  44124. case ShortType:
  44125. formatGPU = GPUTextureFormat.RGBA16Sint;
  44126. break;
  44127. case UnsignedShortType:
  44128. formatGPU = GPUTextureFormat.RGBA16Uint;
  44129. break;
  44130. case UnsignedIntType:
  44131. formatGPU = GPUTextureFormat.RGBA32Uint;
  44132. break;
  44133. case IntType:
  44134. formatGPU = GPUTextureFormat.RGBA32Sint;
  44135. break;
  44136. case UnsignedByteType:
  44137. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  44138. break;
  44139. case HalfFloatType:
  44140. formatGPU = GPUTextureFormat.RGBA16Float;
  44141. break;
  44142. case FloatType:
  44143. formatGPU = GPUTextureFormat.RGBA32Float;
  44144. break;
  44145. default:
  44146. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  44147. }
  44148. break;
  44149. case RGBFormat:
  44150. switch ( type ) {
  44151. case UnsignedInt5999Type:
  44152. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  44153. break;
  44154. default:
  44155. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  44156. }
  44157. break;
  44158. case RedFormat:
  44159. switch ( type ) {
  44160. case ByteType:
  44161. formatGPU = GPUTextureFormat.R8Snorm;
  44162. break;
  44163. case ShortType:
  44164. formatGPU = GPUTextureFormat.R16Sint;
  44165. break;
  44166. case UnsignedShortType:
  44167. formatGPU = GPUTextureFormat.R16Uint;
  44168. break;
  44169. case UnsignedIntType:
  44170. formatGPU = GPUTextureFormat.R32Uint;
  44171. break;
  44172. case IntType:
  44173. formatGPU = GPUTextureFormat.R32Sint;
  44174. break;
  44175. case UnsignedByteType:
  44176. formatGPU = GPUTextureFormat.R8Unorm;
  44177. break;
  44178. case HalfFloatType:
  44179. formatGPU = GPUTextureFormat.R16Float;
  44180. break;
  44181. case FloatType:
  44182. formatGPU = GPUTextureFormat.R32Float;
  44183. break;
  44184. default:
  44185. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  44186. }
  44187. break;
  44188. case RGFormat:
  44189. switch ( type ) {
  44190. case ByteType:
  44191. formatGPU = GPUTextureFormat.RG8Snorm;
  44192. break;
  44193. case ShortType:
  44194. formatGPU = GPUTextureFormat.RG16Sint;
  44195. break;
  44196. case UnsignedShortType:
  44197. formatGPU = GPUTextureFormat.RG16Uint;
  44198. break;
  44199. case UnsignedIntType:
  44200. formatGPU = GPUTextureFormat.RG32Uint;
  44201. break;
  44202. case IntType:
  44203. formatGPU = GPUTextureFormat.RG32Sint;
  44204. break;
  44205. case UnsignedByteType:
  44206. formatGPU = GPUTextureFormat.RG8Unorm;
  44207. break;
  44208. case HalfFloatType:
  44209. formatGPU = GPUTextureFormat.RG16Float;
  44210. break;
  44211. case FloatType:
  44212. formatGPU = GPUTextureFormat.RG32Float;
  44213. break;
  44214. default:
  44215. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  44216. }
  44217. break;
  44218. case DepthFormat:
  44219. switch ( type ) {
  44220. case UnsignedShortType:
  44221. formatGPU = GPUTextureFormat.Depth16Unorm;
  44222. break;
  44223. case UnsignedIntType:
  44224. formatGPU = GPUTextureFormat.Depth24Plus;
  44225. break;
  44226. case FloatType:
  44227. formatGPU = GPUTextureFormat.Depth32Float;
  44228. break;
  44229. default:
  44230. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  44231. }
  44232. break;
  44233. case DepthStencilFormat:
  44234. switch ( type ) {
  44235. case UnsignedInt248Type:
  44236. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  44237. break;
  44238. case FloatType:
  44239. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  44240. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  44241. }
  44242. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  44243. break;
  44244. default:
  44245. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  44246. }
  44247. break;
  44248. case RedIntegerFormat:
  44249. switch ( type ) {
  44250. case IntType:
  44251. formatGPU = GPUTextureFormat.R32Sint;
  44252. break;
  44253. case UnsignedIntType:
  44254. formatGPU = GPUTextureFormat.R32Uint;
  44255. break;
  44256. default:
  44257. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  44258. }
  44259. break;
  44260. case RGIntegerFormat:
  44261. switch ( type ) {
  44262. case IntType:
  44263. formatGPU = GPUTextureFormat.RG32Sint;
  44264. break;
  44265. case UnsignedIntType:
  44266. formatGPU = GPUTextureFormat.RG32Uint;
  44267. break;
  44268. default:
  44269. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  44270. }
  44271. break;
  44272. case RGBAIntegerFormat:
  44273. switch ( type ) {
  44274. case IntType:
  44275. formatGPU = GPUTextureFormat.RGBA32Sint;
  44276. break;
  44277. case UnsignedIntType:
  44278. formatGPU = GPUTextureFormat.RGBA32Uint;
  44279. break;
  44280. default:
  44281. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  44282. }
  44283. break;
  44284. default:
  44285. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  44286. }
  44287. }
  44288. return formatGPU;
  44289. }
  44290. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  44291. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  44292. const wgslTypeLib$1 = {
  44293. 'f32': 'float',
  44294. 'i32': 'int',
  44295. 'u32': 'uint',
  44296. 'bool': 'bool',
  44297. 'vec2<f32>': 'vec2',
  44298. 'vec2<i32>': 'ivec2',
  44299. 'vec2<u32>': 'uvec2',
  44300. 'vec2<bool>': 'bvec2',
  44301. 'vec2f': 'vec2',
  44302. 'vec2i': 'ivec2',
  44303. 'vec2u': 'uvec2',
  44304. 'vec2b': 'bvec2',
  44305. 'vec3<f32>': 'vec3',
  44306. 'vec3<i32>': 'ivec3',
  44307. 'vec3<u32>': 'uvec3',
  44308. 'vec3<bool>': 'bvec3',
  44309. 'vec3f': 'vec3',
  44310. 'vec3i': 'ivec3',
  44311. 'vec3u': 'uvec3',
  44312. 'vec3b': 'bvec3',
  44313. 'vec4<f32>': 'vec4',
  44314. 'vec4<i32>': 'ivec4',
  44315. 'vec4<u32>': 'uvec4',
  44316. 'vec4<bool>': 'bvec4',
  44317. 'vec4f': 'vec4',
  44318. 'vec4i': 'ivec4',
  44319. 'vec4u': 'uvec4',
  44320. 'vec4b': 'bvec4',
  44321. 'mat2x2<f32>': 'mat2',
  44322. 'mat2x2f': 'mat2',
  44323. 'mat3x3<f32>': 'mat3',
  44324. 'mat3x3f': 'mat3',
  44325. 'mat4x4<f32>': 'mat4',
  44326. 'mat4x4f': 'mat4',
  44327. 'sampler': 'sampler',
  44328. 'texture_1d': 'texture',
  44329. 'texture_2d': 'texture',
  44330. 'texture_2d_array': 'texture',
  44331. 'texture_multisampled_2d': 'cubeTexture',
  44332. 'texture_depth_2d': 'depthTexture',
  44333. 'texture_depth_multisampled_2d': 'depthTexture',
  44334. 'texture_3d': 'texture3D',
  44335. 'texture_cube': 'cubeTexture',
  44336. 'texture_cube_array': 'cubeTexture',
  44337. 'texture_storage_1d': 'storageTexture',
  44338. 'texture_storage_2d': 'storageTexture',
  44339. 'texture_storage_2d_array': 'storageTexture',
  44340. 'texture_storage_3d': 'storageTexture'
  44341. };
  44342. const parse = ( source ) => {
  44343. source = source.trim();
  44344. const declaration = source.match( declarationRegexp );
  44345. if ( declaration !== null && declaration.length === 4 ) {
  44346. const inputsCode = declaration[ 2 ];
  44347. const propsMatches = [];
  44348. let match = null;
  44349. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  44350. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  44351. }
  44352. // Process matches to correctly pair names and types
  44353. const inputs = [];
  44354. for ( let i = 0; i < propsMatches.length; i ++ ) {
  44355. const { name, type } = propsMatches[ i ];
  44356. let resolvedType = type;
  44357. if ( resolvedType.startsWith( 'ptr' ) ) {
  44358. resolvedType = 'pointer';
  44359. } else {
  44360. if ( resolvedType.startsWith( 'texture' ) ) {
  44361. resolvedType = type.split( '<' )[ 0 ];
  44362. }
  44363. resolvedType = wgslTypeLib$1[ resolvedType ];
  44364. }
  44365. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  44366. }
  44367. const blockCode = source.substring( declaration[ 0 ].length );
  44368. const outputType = declaration[ 3 ] || 'void';
  44369. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  44370. const type = wgslTypeLib$1[ outputType ] || outputType;
  44371. return {
  44372. type,
  44373. inputs,
  44374. name,
  44375. inputsCode,
  44376. blockCode,
  44377. outputType
  44378. };
  44379. } else {
  44380. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  44381. }
  44382. };
  44383. /**
  44384. * This class represents a WSL node function.
  44385. *
  44386. * @augments NodeFunction
  44387. */
  44388. class WGSLNodeFunction extends NodeFunction {
  44389. /**
  44390. * Constructs a new WGSL node function.
  44391. *
  44392. * @param {String} source - The WGSL source.
  44393. */
  44394. constructor( source ) {
  44395. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  44396. super( type, inputs, name );
  44397. this.inputsCode = inputsCode;
  44398. this.blockCode = blockCode;
  44399. this.outputType = outputType;
  44400. }
  44401. /**
  44402. * This method returns the WGSL code of the node function.
  44403. *
  44404. * @param {String} [name=this.name] - The function's name.
  44405. * @return {String} The shader code.
  44406. */
  44407. getCode( name = this.name ) {
  44408. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  44409. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  44410. }
  44411. }
  44412. /**
  44413. * A WGSL node parser.
  44414. *
  44415. * @augments NodeParser
  44416. */
  44417. class WGSLNodeParser extends NodeParser {
  44418. /**
  44419. * The method parses the given WGSL code an returns a node function.
  44420. *
  44421. * @param {String} source - The WGSL code.
  44422. * @return {WGSLNodeFunction} A node function.
  44423. */
  44424. parseFunction( source ) {
  44425. return new WGSLNodeFunction( source );
  44426. }
  44427. }
  44428. // GPUShaderStage is not defined in browsers not supporting WebGPU
  44429. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  44430. const accessNames = {
  44431. [ NodeAccess.READ_ONLY ]: 'read',
  44432. [ NodeAccess.WRITE_ONLY ]: 'write',
  44433. [ NodeAccess.READ_WRITE ]: 'read_write'
  44434. };
  44435. const wrapNames = {
  44436. [ RepeatWrapping ]: 'repeat',
  44437. [ ClampToEdgeWrapping ]: 'clamp',
  44438. [ MirroredRepeatWrapping ]: 'mirror'
  44439. };
  44440. const gpuShaderStageLib = {
  44441. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  44442. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  44443. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  44444. };
  44445. const supports = {
  44446. instance: true,
  44447. swizzleAssign: false,
  44448. storageBuffer: true
  44449. };
  44450. const wgslFnOpLib = {
  44451. '^^': 'tsl_xor'
  44452. };
  44453. const wgslTypeLib = {
  44454. float: 'f32',
  44455. int: 'i32',
  44456. uint: 'u32',
  44457. bool: 'bool',
  44458. color: 'vec3<f32>',
  44459. vec2: 'vec2<f32>',
  44460. ivec2: 'vec2<i32>',
  44461. uvec2: 'vec2<u32>',
  44462. bvec2: 'vec2<bool>',
  44463. vec3: 'vec3<f32>',
  44464. ivec3: 'vec3<i32>',
  44465. uvec3: 'vec3<u32>',
  44466. bvec3: 'vec3<bool>',
  44467. vec4: 'vec4<f32>',
  44468. ivec4: 'vec4<i32>',
  44469. uvec4: 'vec4<u32>',
  44470. bvec4: 'vec4<bool>',
  44471. mat2: 'mat2x2<f32>',
  44472. mat3: 'mat3x3<f32>',
  44473. mat4: 'mat4x4<f32>'
  44474. };
  44475. const wgslCodeCache = {};
  44476. const wgslPolyfill = {
  44477. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  44478. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  44479. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  44480. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  44481. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  44482. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  44483. 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 ); }' ),
  44484. 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 ); }' ),
  44485. 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 ); }' ),
  44486. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  44487. 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 ); }' ),
  44488. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  44489. biquadraticTexture: new CodeNode( /* wgsl */`
  44490. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  44491. let res = vec2f( iRes );
  44492. let uvScaled = coord * res;
  44493. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  44494. // https://www.shadertoy.com/view/WtyXRy
  44495. let uv = uvWrapping - 0.5;
  44496. let iuv = floor( uv );
  44497. let f = fract( uv );
  44498. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  44499. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  44500. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  44501. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  44502. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  44503. }
  44504. ` )
  44505. };
  44506. const wgslMethods = {
  44507. dFdx: 'dpdx',
  44508. dFdy: '- dpdy',
  44509. mod_float: 'tsl_mod_float',
  44510. mod_vec2: 'tsl_mod_vec2',
  44511. mod_vec3: 'tsl_mod_vec3',
  44512. mod_vec4: 'tsl_mod_vec4',
  44513. equals_bool: 'tsl_equals_bool',
  44514. equals_bvec2: 'tsl_equals_bvec2',
  44515. equals_bvec3: 'tsl_equals_bvec3',
  44516. equals_bvec4: 'tsl_equals_bvec4',
  44517. inversesqrt: 'inverseSqrt',
  44518. bitcast: 'bitcast<f32>'
  44519. };
  44520. // WebGPU issue: does not support pow() with negative base on Windows
  44521. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  44522. 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 ); }' );
  44523. 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 ] );
  44524. 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 ] );
  44525. 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 ] );
  44526. wgslMethods.pow_float = 'tsl_pow_float';
  44527. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  44528. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  44529. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  44530. }
  44531. //
  44532. let diagnostics = '';
  44533. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  44534. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  44535. }
  44536. /**
  44537. * A node builder targeting WGSL.
  44538. *
  44539. * This module generates WGSL shader code from node materials and also
  44540. * generates the respective bindings and vertex buffer definitions. These
  44541. * data are later used by the renderer to create render and compute pipelines
  44542. * for render objects.
  44543. *
  44544. * @augments NodeBuilder
  44545. */
  44546. class WGSLNodeBuilder extends NodeBuilder {
  44547. /**
  44548. * Constructs a new WGSL node builder renderer.
  44549. *
  44550. * @param {Object3D} object - The 3D object.
  44551. * @param {Renderer} renderer - The renderer.
  44552. */
  44553. constructor( object, renderer ) {
  44554. super( object, renderer, new WGSLNodeParser() );
  44555. /**
  44556. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  44557. * another dictionary which manages UBOs per group ('render','frame','object').
  44558. *
  44559. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  44560. */
  44561. this.uniformGroups = {};
  44562. /**
  44563. * A dictionary that holds for each shader stage a Map of builtins.
  44564. *
  44565. * @type {Object<String,Map<String,Object>>}
  44566. */
  44567. this.builtins = {};
  44568. /**
  44569. * A dictionary that holds for each shader stage a Set of directives.
  44570. *
  44571. * @type {Object<String,Set<String>>}
  44572. */
  44573. this.directives = {};
  44574. /**
  44575. * A map for managing scope arrays. Only relevant for when using
  44576. * {@link module:WorkgroupInfoNode} in context of compute shaders.
  44577. *
  44578. * @type {Map<String,Object>}
  44579. */
  44580. this.scopedArrays = new Map();
  44581. }
  44582. /**
  44583. * Checks if the given texture requires a manual conversion to the working color space.
  44584. *
  44585. * @param {Texture} texture - The texture to check.
  44586. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  44587. */
  44588. needsToWorkingColorSpace( texture ) {
  44589. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  44590. }
  44591. /**
  44592. * Generates the WGSL snippet for sampled textures.
  44593. *
  44594. * @private
  44595. * @param {Texture} texture - The texture.
  44596. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44597. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44598. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44599. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44600. * @return {String} The WGSL snippet.
  44601. */
  44602. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44603. if ( shaderStage === 'fragment' ) {
  44604. if ( depthSnippet ) {
  44605. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  44606. } else {
  44607. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  44608. }
  44609. } else if ( this.isFilteredTexture( texture ) ) {
  44610. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  44611. } else {
  44612. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  44613. }
  44614. }
  44615. /**
  44616. * Generates the WGSL snippet when sampling video textures.
  44617. *
  44618. * @private
  44619. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  44620. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44621. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44622. * @return {String} The WGSL snippet.
  44623. */
  44624. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  44625. if ( shaderStage === 'fragment' ) {
  44626. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  44627. } else {
  44628. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  44629. }
  44630. }
  44631. /**
  44632. * Generates the WGSL snippet when sampling textures with explicit mip level.
  44633. *
  44634. * @private
  44635. * @param {Texture} texture - The texture.
  44636. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44637. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44638. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44639. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44640. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44641. * @return {String} The WGSL snippet.
  44642. */
  44643. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44644. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  44645. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  44646. } else if ( this.isFilteredTexture( texture ) ) {
  44647. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  44648. } else {
  44649. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  44650. }
  44651. }
  44652. /**
  44653. * Generates a wrap function used in context of textures.
  44654. *
  44655. * @param {Texture} texture - The texture to generate the function for.
  44656. * @return {String} The name of the generated function.
  44657. */
  44658. generateWrapFunction( texture ) {
  44659. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  44660. let nodeCode = wgslCodeCache[ functionName ];
  44661. if ( nodeCode === undefined ) {
  44662. const includes = [];
  44663. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  44664. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  44665. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  44666. const addWrapSnippet = ( wrap, axis ) => {
  44667. if ( wrap === RepeatWrapping ) {
  44668. includes.push( wgslPolyfill.repeatWrapping_float );
  44669. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  44670. } else if ( wrap === ClampToEdgeWrapping ) {
  44671. includes.push( wgslPolyfill.clampWrapping_float );
  44672. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  44673. } else if ( wrap === MirroredRepeatWrapping ) {
  44674. includes.push( wgslPolyfill.mirrorWrapping_float );
  44675. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  44676. } else {
  44677. code += `\t\tcoord.${ axis }`;
  44678. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  44679. }
  44680. };
  44681. addWrapSnippet( texture.wrapS, 'x' );
  44682. code += ',\n';
  44683. addWrapSnippet( texture.wrapT, 'y' );
  44684. if ( texture.isData3DTexture ) {
  44685. code += ',\n';
  44686. addWrapSnippet( texture.wrapR, 'z' );
  44687. }
  44688. code += '\n\t);\n\n}\n';
  44689. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  44690. }
  44691. nodeCode.build( this );
  44692. return functionName;
  44693. }
  44694. /**
  44695. * Generates the array declaration string.
  44696. *
  44697. * @param {String} type - The type.
  44698. * @param {Number?} [count] - The count.
  44699. * @return {String} The generated value as a shader string.
  44700. */
  44701. generateArrayDeclaration( type, count ) {
  44702. return `array< ${ this.getType( type ) }, ${ count } >`;
  44703. }
  44704. /**
  44705. * Generates a WGSL variable that holds the texture dimension of the given texture.
  44706. * It also returns information about the the number of layers (elements) of an arrayed
  44707. * texture as well as the cube face count of cube textures.
  44708. *
  44709. * @param {Texture} texture - The texture to generate the function for.
  44710. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  44711. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44712. * @return {String} The name of the dimension variable.
  44713. */
  44714. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  44715. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  44716. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  44717. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  44718. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  44719. let textureDimensionsParams;
  44720. let dimensionType;
  44721. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  44722. const isMultisampled = primarySamples > 1;
  44723. if ( texture.isData3DTexture ) {
  44724. dimensionType = 'vec3<u32>';
  44725. } else {
  44726. // Regular 2D textures, depth textures, etc.
  44727. dimensionType = 'vec2<u32>';
  44728. }
  44729. // Build parameters string based on texture type and multisampling
  44730. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  44731. textureDimensionsParams = textureProperty;
  44732. } else {
  44733. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  44734. }
  44735. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  44736. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  44737. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  44738. textureData.arrayLayerCount = new VarNode(
  44739. new ExpressionNode(
  44740. `textureNumLayers(${textureProperty})`,
  44741. 'u32'
  44742. )
  44743. );
  44744. }
  44745. // For cube textures, we know it's always 6 faces
  44746. if ( texture.isTextureCube ) {
  44747. textureData.cubeFaceCount = new VarNode(
  44748. new ExpressionNode( '6u', 'u32' )
  44749. );
  44750. }
  44751. }
  44752. return textureDimensionNode.build( this );
  44753. }
  44754. /**
  44755. * Generates the WGSL snippet for a manual filtered texture.
  44756. *
  44757. * @param {Texture} texture - The texture.
  44758. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44759. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44760. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44761. * @return {String} The WGSL snippet.
  44762. */
  44763. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  44764. this._include( 'biquadraticTexture' );
  44765. const wrapFunction = this.generateWrapFunction( texture );
  44766. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  44767. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  44768. }
  44769. /**
  44770. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  44771. * Since it's a lookup, no sampling or filtering is applied.
  44772. *
  44773. * @param {Texture} texture - The texture.
  44774. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44775. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44776. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44777. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44778. * @return {String} The WGSL snippet.
  44779. */
  44780. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  44781. const wrapFunction = this.generateWrapFunction( texture );
  44782. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  44783. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  44784. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  44785. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  44786. }
  44787. /**
  44788. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  44789. *
  44790. * @param {Texture} texture - The texture.
  44791. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44792. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44793. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44794. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44795. * @return {String} The WGSL snippet.
  44796. */
  44797. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  44798. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  44799. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  44800. } else if ( depthSnippet ) {
  44801. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  44802. } else {
  44803. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  44804. }
  44805. }
  44806. /**
  44807. * Generates the WGSL snippet that writes a single texel to a texture.
  44808. *
  44809. * @param {Texture} texture - The texture.
  44810. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44811. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44812. * @param {String} valueSnippet - A WGSL snippet that represent the new texel value.
  44813. * @return {String} The WGSL snippet.
  44814. */
  44815. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  44816. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  44817. }
  44818. /**
  44819. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  44820. *
  44821. * @param {Texture} texture - The texture.
  44822. * @return {Boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  44823. */
  44824. isSampleCompare( texture ) {
  44825. return texture.isDepthTexture === true && texture.compareFunction !== null;
  44826. }
  44827. /**
  44828. * Returns `true` if the given texture is unfilterable.
  44829. *
  44830. * @param {Texture} texture - The texture.
  44831. * @return {Boolean} Whether the given texture is unfilterable or not.
  44832. */
  44833. isUnfilterable( texture ) {
  44834. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  44835. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  44836. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  44837. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  44838. }
  44839. /**
  44840. * Generates the WGSL snippet for sampling/loading the given texture.
  44841. *
  44842. * @param {Texture} texture - The texture.
  44843. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44844. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44845. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44846. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44847. * @return {String} The WGSL snippet.
  44848. */
  44849. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44850. let snippet = null;
  44851. if ( texture.isVideoTexture === true ) {
  44852. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  44853. } else if ( this.isUnfilterable( texture ) ) {
  44854. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  44855. } else {
  44856. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  44857. }
  44858. return snippet;
  44859. }
  44860. /**
  44861. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  44862. *
  44863. * @param {Texture} texture - The texture.
  44864. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44865. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44866. * @param {Array<String>} gradSnippet - An array holding both gradient WGSL snippets.
  44867. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44868. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44869. * @return {String} The WGSL snippet.
  44870. */
  44871. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44872. if ( shaderStage === 'fragment' ) {
  44873. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  44874. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  44875. } else {
  44876. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  44877. }
  44878. }
  44879. /**
  44880. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  44881. * against a reference value.
  44882. *
  44883. * @param {Texture} texture - The texture.
  44884. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44885. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44886. * @param {String} compareSnippet - A WGSL snippet that represents the reference value.
  44887. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44888. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44889. * @return {String} The WGSL snippet.
  44890. */
  44891. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44892. if ( shaderStage === 'fragment' ) {
  44893. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  44894. } else {
  44895. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  44896. }
  44897. }
  44898. /**
  44899. * Generates the WGSL snippet when sampling textures with explicit mip level.
  44900. *
  44901. * @param {Texture} texture - The texture.
  44902. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44903. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44904. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  44905. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44906. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44907. * @return {String} The WGSL snippet.
  44908. */
  44909. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44910. let snippet = null;
  44911. if ( texture.isVideoTexture === true ) {
  44912. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  44913. } else {
  44914. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  44915. }
  44916. return snippet;
  44917. }
  44918. /**
  44919. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  44920. *
  44921. * @param {Texture} texture - The texture.
  44922. * @param {String} textureProperty - The name of the texture uniform in the shader.
  44923. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  44924. * @param {String} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  44925. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  44926. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44927. * @return {String} The WGSL snippet.
  44928. */
  44929. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  44930. if ( shaderStage === 'fragment' ) {
  44931. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  44932. } else {
  44933. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  44934. }
  44935. }
  44936. /**
  44937. * Returns a WGSL snippet that represents the property name of the given node.
  44938. *
  44939. * @param {Node} node - The node.
  44940. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44941. * @return {String} The property name.
  44942. */
  44943. getPropertyName( node, shaderStage = this.shaderStage ) {
  44944. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  44945. if ( shaderStage === 'vertex' ) {
  44946. return `varyings.${ node.name }`;
  44947. }
  44948. } else if ( node.isNodeUniform === true ) {
  44949. const name = node.name;
  44950. const type = node.type;
  44951. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44952. return name;
  44953. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  44954. if ( this.isCustomStruct( node ) ) {
  44955. return name;
  44956. }
  44957. return name + '.value';
  44958. } else {
  44959. return node.groupNode.name + '.' + name;
  44960. }
  44961. }
  44962. return super.getPropertyName( node );
  44963. }
  44964. /**
  44965. * Returns the output struct name.
  44966. *
  44967. * @return {String} The name of the output struct.
  44968. */
  44969. getOutputStructName() {
  44970. return 'output';
  44971. }
  44972. /**
  44973. * Returns uniforms group count for the given shader stage.
  44974. *
  44975. * @private
  44976. * @param {String} shaderStage - The shader stage.
  44977. * @return {Number} The uniforms group count for the given shader stage.
  44978. */
  44979. _getUniformGroupCount( shaderStage ) {
  44980. return Object.keys( this.uniforms[ shaderStage ] ).length;
  44981. }
  44982. /**
  44983. * Returns the native shader operator name for a given generic name.
  44984. *
  44985. * @param {String} op - The operator name to resolve.
  44986. * @return {String} The resolved operator name.
  44987. */
  44988. getFunctionOperator( op ) {
  44989. const fnOp = wgslFnOpLib[ op ];
  44990. if ( fnOp !== undefined ) {
  44991. this._include( fnOp );
  44992. return fnOp;
  44993. }
  44994. return null;
  44995. }
  44996. /**
  44997. * Returns the node access for the given node and shader stage.
  44998. *
  44999. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  45000. * @param {String} shaderStage - The shader stage.
  45001. * @return {String} The node access.
  45002. */
  45003. getNodeAccess( node, shaderStage ) {
  45004. if ( shaderStage !== 'compute' )
  45005. return NodeAccess.READ_ONLY;
  45006. return node.access;
  45007. }
  45008. /**
  45009. * Returns A WGSL snippet representing the storage access.
  45010. *
  45011. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  45012. * @param {String} shaderStage - The shader stage.
  45013. * @return {String} The WGSL snippet representing the storage access.
  45014. */
  45015. getStorageAccess( node, shaderStage ) {
  45016. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  45017. }
  45018. /**
  45019. * This method is one of the more important ones since it's responsible
  45020. * for generating a matching binding instance for the given uniform node.
  45021. *
  45022. * These bindings are later used in the renderer to create bind groups
  45023. * and layouts.
  45024. *
  45025. * @param {UniformNode} node - The uniform node.
  45026. * @param {String} type - The node data type.
  45027. * @param {String} shaderStage - The shader stage.
  45028. * @param {String?} [name=null] - An optional uniform name.
  45029. * @return {NodeUniform} The node uniform object.
  45030. */
  45031. getUniformFromNode( node, type, shaderStage, name = null ) {
  45032. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  45033. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  45034. if ( nodeData.uniformGPU === undefined ) {
  45035. let uniformGPU;
  45036. const group = node.groupNode;
  45037. const groupName = group.name;
  45038. const bindings = this.getBindGroupArray( groupName, shaderStage );
  45039. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  45040. let texture = null;
  45041. const access = this.getNodeAccess( node, shaderStage );
  45042. if ( type === 'texture' || type === 'storageTexture' ) {
  45043. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  45044. } else if ( type === 'cubeTexture' ) {
  45045. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  45046. } else if ( type === 'texture3D' ) {
  45047. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  45048. }
  45049. texture.store = node.isStorageTextureNode === true;
  45050. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45051. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  45052. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  45053. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45054. bindings.push( sampler, texture );
  45055. uniformGPU = [ sampler, texture ];
  45056. } else {
  45057. bindings.push( texture );
  45058. uniformGPU = [ texture ];
  45059. }
  45060. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  45061. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  45062. const buffer = new bufferClass( node, group );
  45063. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45064. bindings.push( buffer );
  45065. uniformGPU = buffer;
  45066. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  45067. } else {
  45068. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  45069. let uniformsGroup = uniformsStage[ groupName ];
  45070. if ( uniformsGroup === undefined ) {
  45071. uniformsGroup = new NodeUniformsGroup( groupName, group );
  45072. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  45073. uniformsStage[ groupName ] = uniformsGroup;
  45074. bindings.push( uniformsGroup );
  45075. }
  45076. uniformGPU = this.getNodeUniform( uniformNode, type );
  45077. uniformsGroup.addUniform( uniformGPU );
  45078. }
  45079. nodeData.uniformGPU = uniformGPU;
  45080. }
  45081. return uniformNode;
  45082. }
  45083. /**
  45084. * This method should be used whenever builtins are required in nodes.
  45085. * The internal builtins data structure will make sure builtins are
  45086. * defined in the WGSL source.
  45087. *
  45088. * @param {String} name - The builtin name.
  45089. * @param {String} property - The property name.
  45090. * @param {String} type - The node data type.
  45091. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45092. * @return {String} The property name.
  45093. */
  45094. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  45095. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  45096. if ( map.has( name ) === false ) {
  45097. map.set( name, {
  45098. name,
  45099. property,
  45100. type
  45101. } );
  45102. }
  45103. return property;
  45104. }
  45105. /**
  45106. * Returns `true` if the given builtin is defined in the given shader stage.
  45107. *
  45108. * @param {String} name - The builtin name.
  45109. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45110. * @return {String} Whether the given builtin is defined in the given shader stage or not.
  45111. */
  45112. hasBuiltin( name, shaderStage = this.shaderStage ) {
  45113. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  45114. }
  45115. /**
  45116. * Returns the vertex index builtin.
  45117. *
  45118. * @return {String} The vertex index.
  45119. */
  45120. getVertexIndex() {
  45121. if ( this.shaderStage === 'vertex' ) {
  45122. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  45123. }
  45124. return 'vertexIndex';
  45125. }
  45126. /**
  45127. * Builds the given shader node.
  45128. *
  45129. * @param {ShaderNodeInternal} shaderNode - The shader node.
  45130. * @return {String} The WGSL function code.
  45131. */
  45132. buildFunctionCode( shaderNode ) {
  45133. const layout = shaderNode.layout;
  45134. const flowData = this.flowShaderNode( shaderNode );
  45135. const parameters = [];
  45136. for ( const input of layout.inputs ) {
  45137. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  45138. }
  45139. //
  45140. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  45141. ${ flowData.vars }
  45142. ${ flowData.code }
  45143. `;
  45144. if ( flowData.result ) {
  45145. code += `\treturn ${ flowData.result };\n`;
  45146. }
  45147. code += '\n}\n';
  45148. //
  45149. return code;
  45150. }
  45151. /**
  45152. * Returns the instance index builtin.
  45153. *
  45154. * @return {String} The instance index.
  45155. */
  45156. getInstanceIndex() {
  45157. if ( this.shaderStage === 'vertex' ) {
  45158. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  45159. }
  45160. return 'instanceIndex';
  45161. }
  45162. /**
  45163. * Returns the invocation local index builtin.
  45164. *
  45165. * @return {String} The invocation local index.
  45166. */
  45167. getInvocationLocalIndex() {
  45168. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  45169. }
  45170. /**
  45171. * Returns the subgroup size builtin.
  45172. *
  45173. * @return {String} The subgroup size.
  45174. */
  45175. getSubgroupSize() {
  45176. this.enableSubGroups();
  45177. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  45178. }
  45179. /**
  45180. * Returns the invocation subgroup index builtin.
  45181. *
  45182. * @return {String} The invocation subgroup index.
  45183. */
  45184. getInvocationSubgroupIndex() {
  45185. this.enableSubGroups();
  45186. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  45187. }
  45188. /**
  45189. * Returns the subgroup index builtin.
  45190. *
  45191. * @return {String} The subgroup index.
  45192. */
  45193. getSubgroupIndex() {
  45194. this.enableSubGroups();
  45195. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  45196. }
  45197. /**
  45198. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  45199. *
  45200. * @return {null} Null.
  45201. */
  45202. getDrawIndex() {
  45203. return null;
  45204. }
  45205. /**
  45206. * Returns the front facing builtin.
  45207. *
  45208. * @return {String} The front facing builtin.
  45209. */
  45210. getFrontFacing() {
  45211. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  45212. }
  45213. /**
  45214. * Returns the frag coord builtin.
  45215. *
  45216. * @return {String} The frag coord builtin.
  45217. */
  45218. getFragCoord() {
  45219. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  45220. }
  45221. /**
  45222. * Returns the frag depth builtin.
  45223. *
  45224. * @return {String} The frag depth builtin.
  45225. */
  45226. getFragDepth() {
  45227. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  45228. }
  45229. /**
  45230. * Returns the clip distances builtin.
  45231. *
  45232. * @return {String} The clip distances builtin.
  45233. */
  45234. getClipDistance() {
  45235. return 'varyings.hw_clip_distances';
  45236. }
  45237. /**
  45238. * Whether to flip texture data along its vertical axis or not.
  45239. *
  45240. * @return {Boolean} Returns always `false` in context of WGSL.
  45241. */
  45242. isFlipY() {
  45243. return false;
  45244. }
  45245. /**
  45246. * Enables the given directive for the given shader stage.
  45247. *
  45248. * @param {String} name - The directive name.
  45249. * @param {String} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  45250. */
  45251. enableDirective( name, shaderStage = this.shaderStage ) {
  45252. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  45253. stage.add( name );
  45254. }
  45255. /**
  45256. * Returns the directives of the given shader stage as a WGSL string.
  45257. *
  45258. * @param {String} shaderStage - The shader stage.
  45259. * @return {String} A WGSL snippet that enables the directives of the given stage.
  45260. */
  45261. getDirectives( shaderStage ) {
  45262. const snippets = [];
  45263. const directives = this.directives[ shaderStage ];
  45264. if ( directives !== undefined ) {
  45265. for ( const directive of directives ) {
  45266. snippets.push( `enable ${directive};` );
  45267. }
  45268. }
  45269. return snippets.join( '\n' );
  45270. }
  45271. /**
  45272. * Enables the 'subgroups' directive.
  45273. */
  45274. enableSubGroups() {
  45275. this.enableDirective( 'subgroups' );
  45276. }
  45277. /**
  45278. * Enables the 'subgroups-f16' directive.
  45279. */
  45280. enableSubgroupsF16() {
  45281. this.enableDirective( 'subgroups-f16' );
  45282. }
  45283. /**
  45284. * Enables the 'clip_distances' directive.
  45285. */
  45286. enableClipDistances() {
  45287. this.enableDirective( 'clip_distances' );
  45288. }
  45289. /**
  45290. * Enables the 'f16' directive.
  45291. */
  45292. enableShaderF16() {
  45293. this.enableDirective( 'f16' );
  45294. }
  45295. /**
  45296. * Enables the 'dual_source_blending' directive.
  45297. */
  45298. enableDualSourceBlending() {
  45299. this.enableDirective( 'dual_source_blending' );
  45300. }
  45301. /**
  45302. * Enables hardware clipping.
  45303. *
  45304. * @param {String} planeCount - The clipping plane count.
  45305. */
  45306. enableHardwareClipping( planeCount ) {
  45307. this.enableClipDistances();
  45308. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  45309. }
  45310. /**
  45311. * Returns the builtins of the given shader stage as a WGSL string.
  45312. *
  45313. * @param {String} shaderStage - The shader stage.
  45314. * @return {String} A WGSL snippet that represents the builtins of the given stage.
  45315. */
  45316. getBuiltins( shaderStage ) {
  45317. const snippets = [];
  45318. const builtins = this.builtins[ shaderStage ];
  45319. if ( builtins !== undefined ) {
  45320. for ( const { name, property, type } of builtins.values() ) {
  45321. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  45322. }
  45323. }
  45324. return snippets.join( ',\n\t' );
  45325. }
  45326. /**
  45327. * This method should be used when a new scoped buffer is used in context of
  45328. * compute shaders. It adds the array to the internal data structure which is
  45329. * later used to generate the respective WGSL.
  45330. *
  45331. * @param {String} name - The array name.
  45332. * @param {String} scope - The scope.
  45333. * @param {String} bufferType - The buffer type.
  45334. * @param {String} bufferCount - The buffer count.
  45335. * @return {String} The array name.
  45336. */
  45337. getScopedArray( name, scope, bufferType, bufferCount ) {
  45338. if ( this.scopedArrays.has( name ) === false ) {
  45339. this.scopedArrays.set( name, {
  45340. name,
  45341. scope,
  45342. bufferType,
  45343. bufferCount
  45344. } );
  45345. }
  45346. return name;
  45347. }
  45348. /**
  45349. * Returns the scoped arrays of the given shader stage as a WGSL string.
  45350. *
  45351. * @param {String} shaderStage - The shader stage.
  45352. * @return {String|undefined} The WGSL snippet that defines the scoped arrays.
  45353. * Returns `undefined` when used in the vertex or fragment stage.
  45354. */
  45355. getScopedArrays( shaderStage ) {
  45356. if ( shaderStage !== 'compute' ) {
  45357. return;
  45358. }
  45359. const snippets = [];
  45360. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  45361. const type = this.getType( bufferType );
  45362. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  45363. }
  45364. return snippets.join( '\n' );
  45365. }
  45366. /**
  45367. * Returns the shader attributes of the given shader stage as a WGSL string.
  45368. *
  45369. * @param {String} shaderStage - The shader stage.
  45370. * @return {String} The WGSL snippet that defines the shader attributes.
  45371. */
  45372. getAttributes( shaderStage ) {
  45373. const snippets = [];
  45374. if ( shaderStage === 'compute' ) {
  45375. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  45376. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  45377. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  45378. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  45379. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  45380. this.enableDirective( 'subgroups', shaderStage );
  45381. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  45382. }
  45383. }
  45384. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  45385. const builtins = this.getBuiltins( 'attribute' );
  45386. if ( builtins ) snippets.push( builtins );
  45387. const attributes = this.getAttributesArray();
  45388. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  45389. const attribute = attributes[ index ];
  45390. const name = attribute.name;
  45391. const type = this.getType( attribute.type );
  45392. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  45393. }
  45394. }
  45395. return snippets.join( ',\n\t' );
  45396. }
  45397. /**
  45398. * Returns the members of the given struct type node as a WGSL string.
  45399. *
  45400. * @param {StructTypeNode} struct - The struct type node.
  45401. * @return {String} The WGSL snippet that defines the struct members.
  45402. */
  45403. getStructMembers( struct ) {
  45404. const snippets = [];
  45405. for ( const member of struct.members ) {
  45406. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  45407. let type = this.getType( member.type );
  45408. if ( member.atomic ) {
  45409. type = 'atomic< ' + type + ' >';
  45410. }
  45411. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  45412. }
  45413. return snippets.join( ',\n' );
  45414. }
  45415. /**
  45416. * Returns the structs of the given shader stage as a WGSL string.
  45417. *
  45418. * @param {String} shaderStage - The shader stage.
  45419. * @return {String} The WGSL snippet that defines the structs.
  45420. */
  45421. getStructs( shaderStage ) {
  45422. let result = '';
  45423. const structs = this.structs[ shaderStage ];
  45424. if ( structs.length > 0 ) {
  45425. const snippets = [];
  45426. for ( const struct of structs ) {
  45427. let snippet = `struct ${ struct.name } {\n`;
  45428. snippet += this.getStructMembers( struct );
  45429. snippet += '\n};';
  45430. snippets.push( snippet );
  45431. }
  45432. result = '\n' + snippets.join( '\n\n' ) + '\n';
  45433. }
  45434. return result;
  45435. }
  45436. /**
  45437. * Returns a WGSL string representing a variable.
  45438. *
  45439. * @param {String} type - The variable's type.
  45440. * @param {String} name - The variable's name.
  45441. * @param {Number?} [count=null] - The array length.
  45442. * @return {String} The WGSL snippet that defines a variable.
  45443. */
  45444. getVar( type, name, count = null ) {
  45445. let snippet = `var ${ name } : `;
  45446. if ( count !== null ) {
  45447. snippet += this.generateArrayDeclaration( type, count );
  45448. } else {
  45449. snippet += this.getType( type );
  45450. }
  45451. return snippet;
  45452. }
  45453. /**
  45454. * Returns the variables of the given shader stage as a WGSL string.
  45455. *
  45456. * @param {String} shaderStage - The shader stage.
  45457. * @return {String} The WGSL snippet that defines the variables.
  45458. */
  45459. getVars( shaderStage ) {
  45460. const snippets = [];
  45461. const vars = this.vars[ shaderStage ];
  45462. if ( vars !== undefined ) {
  45463. for ( const variable of vars ) {
  45464. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  45465. }
  45466. }
  45467. return `\n${ snippets.join( '\n' ) }\n`;
  45468. }
  45469. /**
  45470. * Returns the varyings of the given shader stage as a WGSL string.
  45471. *
  45472. * @param {String} shaderStage - The shader stage.
  45473. * @return {String} The WGSL snippet that defines the varyings.
  45474. */
  45475. getVaryings( shaderStage ) {
  45476. const snippets = [];
  45477. if ( shaderStage === 'vertex' ) {
  45478. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  45479. }
  45480. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  45481. const varyings = this.varyings;
  45482. const vars = this.vars[ shaderStage ];
  45483. for ( let index = 0; index < varyings.length; index ++ ) {
  45484. const varying = varyings[ index ];
  45485. if ( varying.needsInterpolation ) {
  45486. let attributesSnippet = `@location( ${index} )`;
  45487. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  45488. attributesSnippet += ' @interpolate( flat )';
  45489. }
  45490. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  45491. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  45492. vars.push( varying );
  45493. }
  45494. }
  45495. }
  45496. const builtins = this.getBuiltins( shaderStage );
  45497. if ( builtins ) snippets.push( builtins );
  45498. const code = snippets.join( ',\n\t' );
  45499. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  45500. }
  45501. isCustomStruct( nodeUniform ) {
  45502. return nodeUniform.value.isStorageBufferAttribute && nodeUniform.node.structTypeNode !== null;
  45503. }
  45504. /**
  45505. * Returns the uniforms of the given shader stage as a WGSL string.
  45506. *
  45507. * @param {String} shaderStage - The shader stage.
  45508. * @return {String} The WGSL snippet that defines the uniforms.
  45509. */
  45510. getUniforms( shaderStage ) {
  45511. const uniforms = this.uniforms[ shaderStage ];
  45512. const bindingSnippets = [];
  45513. const bufferSnippets = [];
  45514. const structSnippets = [];
  45515. const uniformGroups = {};
  45516. for ( const uniform of uniforms ) {
  45517. const groupName = uniform.groupNode.name;
  45518. const uniformIndexes = this.bindingsIndexes[ groupName ];
  45519. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  45520. const texture = uniform.node.value;
  45521. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  45522. if ( this.isSampleCompare( texture ) ) {
  45523. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  45524. } else {
  45525. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  45526. }
  45527. }
  45528. let textureType;
  45529. let multisampled = '';
  45530. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  45531. if ( primarySamples > 1 ) {
  45532. multisampled = '_multisampled';
  45533. }
  45534. if ( texture.isCubeTexture === true ) {
  45535. textureType = 'texture_cube<f32>';
  45536. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  45537. textureType = 'texture_2d_array<f32>';
  45538. } else if ( texture.isDepthTexture === true ) {
  45539. textureType = `texture_depth${multisampled}_2d`;
  45540. } else if ( texture.isVideoTexture === true ) {
  45541. textureType = 'texture_external';
  45542. } else if ( texture.isData3DTexture === true ) {
  45543. textureType = 'texture_3d<f32>';
  45544. } else if ( uniform.node.isStorageTextureNode === true ) {
  45545. const format = getFormat( texture );
  45546. const access = this.getStorageAccess( uniform.node, shaderStage );
  45547. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  45548. } else {
  45549. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  45550. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  45551. }
  45552. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  45553. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  45554. const bufferNode = uniform.node;
  45555. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  45556. const bufferCount = bufferNode.bufferCount;
  45557. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  45558. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  45559. if ( this.isCustomStruct( uniform ) ) {
  45560. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  45561. } else {
  45562. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  45563. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  45564. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  45565. }
  45566. } else {
  45567. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  45568. const groupName = uniform.groupNode.name;
  45569. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  45570. index: uniformIndexes.binding ++,
  45571. id: uniformIndexes.group,
  45572. snippets: []
  45573. } );
  45574. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  45575. }
  45576. }
  45577. for ( const name in uniformGroups ) {
  45578. const group = uniformGroups[ name ];
  45579. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  45580. }
  45581. let code = bindingSnippets.join( '\n' );
  45582. code += bufferSnippets.join( '\n' );
  45583. code += structSnippets.join( '\n' );
  45584. return code;
  45585. }
  45586. /**
  45587. * Controls the code build of the shader stages.
  45588. */
  45589. buildCode() {
  45590. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  45591. this.sortBindingGroups();
  45592. for ( const shaderStage in shadersData ) {
  45593. this.shaderStage = shaderStage;
  45594. const stageData = shadersData[ shaderStage ];
  45595. stageData.uniforms = this.getUniforms( shaderStage );
  45596. stageData.attributes = this.getAttributes( shaderStage );
  45597. stageData.varyings = this.getVaryings( shaderStage );
  45598. stageData.structs = this.getStructs( shaderStage );
  45599. stageData.vars = this.getVars( shaderStage );
  45600. stageData.codes = this.getCodes( shaderStage );
  45601. stageData.directives = this.getDirectives( shaderStage );
  45602. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  45603. //
  45604. let flow = '// code\n\n';
  45605. flow += this.flowCode[ shaderStage ];
  45606. const flowNodes = this.flowNodes[ shaderStage ];
  45607. const mainNode = flowNodes[ flowNodes.length - 1 ];
  45608. const outputNode = mainNode.outputNode;
  45609. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  45610. for ( const node of flowNodes ) {
  45611. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  45612. const slotName = node.name;
  45613. if ( slotName ) {
  45614. if ( flow.length > 0 ) flow += '\n';
  45615. flow += `\t// flow -> ${ slotName }\n`;
  45616. }
  45617. flow += `${ flowSlotData.code }\n\t`;
  45618. if ( node === mainNode && shaderStage !== 'compute' ) {
  45619. flow += '// result\n\n\t';
  45620. if ( shaderStage === 'vertex' ) {
  45621. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  45622. } else if ( shaderStage === 'fragment' ) {
  45623. if ( isOutputStruct ) {
  45624. stageData.returnType = outputNode.getNodeType( this );
  45625. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  45626. flow += `return ${ flowSlotData.result };`;
  45627. } else {
  45628. let structSnippet = '\t@location(0) color: vec4<f32>';
  45629. const builtins = this.getBuiltins( 'output' );
  45630. if ( builtins ) structSnippet += ',\n\t' + builtins;
  45631. stageData.returnType = 'OutputStruct';
  45632. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  45633. stageData.structs += '\nvar<private> output : OutputStruct;';
  45634. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  45635. }
  45636. }
  45637. }
  45638. }
  45639. stageData.flow = flow;
  45640. }
  45641. this.shaderStage = null;
  45642. if ( this.material !== null ) {
  45643. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  45644. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  45645. } else {
  45646. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  45647. }
  45648. }
  45649. /**
  45650. * Returns the native shader method name for a given generic name.
  45651. *
  45652. * @param {String} method - The method name to resolve.
  45653. * @param {String} [output=null] - An optional output.
  45654. * @return {String} The resolved WGSL method name.
  45655. */
  45656. getMethod( method, output = null ) {
  45657. let wgslMethod;
  45658. if ( output !== null ) {
  45659. wgslMethod = this._getWGSLMethod( method + '_' + output );
  45660. }
  45661. if ( wgslMethod === undefined ) {
  45662. wgslMethod = this._getWGSLMethod( method );
  45663. }
  45664. return wgslMethod || method;
  45665. }
  45666. /**
  45667. * Returns the WGSL type of the given node data type.
  45668. *
  45669. * @param {String} type - The node data type.
  45670. * @return {String} The WGSL type.
  45671. */
  45672. getType( type ) {
  45673. return wgslTypeLib[ type ] || type;
  45674. }
  45675. /**
  45676. * Whether the requested feature is available or not.
  45677. *
  45678. * @param {String} name - The requested feature.
  45679. * @return {Boolean} Whether the requested feature is supported or not.
  45680. */
  45681. isAvailable( name ) {
  45682. let result = supports[ name ];
  45683. if ( result === undefined ) {
  45684. if ( name === 'float32Filterable' ) {
  45685. result = this.renderer.hasFeature( 'float32-filterable' );
  45686. } else if ( name === 'clipDistance' ) {
  45687. result = this.renderer.hasFeature( 'clip-distances' );
  45688. }
  45689. supports[ name ] = result;
  45690. }
  45691. return result;
  45692. }
  45693. /**
  45694. * Returns the native shader method name for a given generic name.
  45695. *
  45696. * @private
  45697. * @param {String} method - The method name to resolve.
  45698. * @return {String} The resolved WGSL method name.
  45699. */
  45700. _getWGSLMethod( method ) {
  45701. if ( wgslPolyfill[ method ] !== undefined ) {
  45702. this._include( method );
  45703. }
  45704. return wgslMethods[ method ];
  45705. }
  45706. /**
  45707. * Includes the given method name into the current
  45708. * function node.
  45709. *
  45710. * @private
  45711. * @param {String} name - The method name to include.
  45712. * @return {CodeNode} The respective code node.
  45713. */
  45714. _include( name ) {
  45715. const codeNode = wgslPolyfill[ name ];
  45716. codeNode.build( this );
  45717. if ( this.currentFunctionNode !== null ) {
  45718. this.currentFunctionNode.includes.push( codeNode );
  45719. }
  45720. return codeNode;
  45721. }
  45722. /**
  45723. * Returns a WGSL vertex shader based on the given shader data.
  45724. *
  45725. * @private
  45726. * @param {Object} shaderData - The shader data.
  45727. * @return {String} The vertex shader.
  45728. */
  45729. _getWGSLVertexCode( shaderData ) {
  45730. return `${ this.getSignature() }
  45731. // directives
  45732. ${shaderData.directives}
  45733. // structs
  45734. ${shaderData.structs}
  45735. // uniforms
  45736. ${shaderData.uniforms}
  45737. // varyings
  45738. ${shaderData.varyings}
  45739. var<private> varyings : VaryingsStruct;
  45740. // codes
  45741. ${shaderData.codes}
  45742. @vertex
  45743. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  45744. // vars
  45745. ${shaderData.vars}
  45746. // flow
  45747. ${shaderData.flow}
  45748. return varyings;
  45749. }
  45750. `;
  45751. }
  45752. /**
  45753. * Returns a WGSL fragment shader based on the given shader data.
  45754. *
  45755. * @private
  45756. * @param {Object} shaderData - The shader data.
  45757. * @return {String} The vertex shader.
  45758. */
  45759. _getWGSLFragmentCode( shaderData ) {
  45760. return `${ this.getSignature() }
  45761. // global
  45762. ${ diagnostics }
  45763. // structs
  45764. ${shaderData.structs}
  45765. // uniforms
  45766. ${shaderData.uniforms}
  45767. // codes
  45768. ${shaderData.codes}
  45769. @fragment
  45770. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  45771. // vars
  45772. ${shaderData.vars}
  45773. // flow
  45774. ${shaderData.flow}
  45775. }
  45776. `;
  45777. }
  45778. /**
  45779. * Returns a WGSL compute shader based on the given shader data.
  45780. *
  45781. * @private
  45782. * @param {Object} shaderData - The shader data.
  45783. * @param {String} workgroupSize - The workgroup size.
  45784. * @return {String} The vertex shader.
  45785. */
  45786. _getWGSLComputeCode( shaderData, workgroupSize ) {
  45787. return `${ this.getSignature() }
  45788. // directives
  45789. ${shaderData.directives}
  45790. // system
  45791. var<private> instanceIndex : u32;
  45792. // locals
  45793. ${shaderData.scopedArrays}
  45794. // structs
  45795. ${shaderData.structs}
  45796. // uniforms
  45797. ${shaderData.uniforms}
  45798. // codes
  45799. ${shaderData.codes}
  45800. @compute @workgroup_size( ${workgroupSize} )
  45801. fn main( ${shaderData.attributes} ) {
  45802. // system
  45803. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  45804. // vars
  45805. ${shaderData.vars}
  45806. // flow
  45807. ${shaderData.flow}
  45808. }
  45809. `;
  45810. }
  45811. /**
  45812. * Returns a WGSL struct based on the given name and variables.
  45813. *
  45814. * @private
  45815. * @param {String} name - The struct name.
  45816. * @param {String} vars - The struct variables.
  45817. * @return {String} The WGSL snippet representing a struct.
  45818. */
  45819. _getWGSLStruct( name, vars ) {
  45820. return `
  45821. struct ${name} {
  45822. ${vars}
  45823. };`;
  45824. }
  45825. /**
  45826. * Returns a WGSL struct binding.
  45827. *
  45828. * @private
  45829. * @param {String} name - The struct name.
  45830. * @param {String} vars - The struct variables.
  45831. * @param {String} access - The access.
  45832. * @param {Number} [binding=0] - The binding index.
  45833. * @param {Number} [group=0] - The group index.
  45834. * @return {String} The WGSL snippet representing a struct binding.
  45835. */
  45836. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  45837. const structName = name + 'Struct';
  45838. const structSnippet = this._getWGSLStruct( structName, vars );
  45839. return `${structSnippet}
  45840. @binding( ${ binding } ) @group( ${ group } )
  45841. var<${access}> ${ name } : ${ structName };`;
  45842. }
  45843. }
  45844. /**
  45845. * A WebGPU backend utility module with common helpers.
  45846. *
  45847. * @private
  45848. */
  45849. class WebGPUUtils {
  45850. /**
  45851. * Constructs a new utility object.
  45852. *
  45853. * @param {WebGPUBackend} backend - The WebGPU backend.
  45854. */
  45855. constructor( backend ) {
  45856. /**
  45857. * A reference to the WebGPU backend.
  45858. *
  45859. * @type {WebGPUBackend}
  45860. */
  45861. this.backend = backend;
  45862. }
  45863. /**
  45864. * Returns the depth/stencil GPU format for the given render context.
  45865. *
  45866. * @param {RenderContext} renderContext - The render context.
  45867. * @return {String} The depth/stencil GPU texture format.
  45868. */
  45869. getCurrentDepthStencilFormat( renderContext ) {
  45870. let format;
  45871. if ( renderContext.depthTexture !== null ) {
  45872. format = this.getTextureFormatGPU( renderContext.depthTexture );
  45873. } else if ( renderContext.depth && renderContext.stencil ) {
  45874. format = GPUTextureFormat.Depth24PlusStencil8;
  45875. } else if ( renderContext.depth ) {
  45876. format = GPUTextureFormat.Depth24Plus;
  45877. }
  45878. return format;
  45879. }
  45880. /**
  45881. * Returns the GPU format for the given texture.
  45882. *
  45883. * @param {Texture} texture - The texture.
  45884. * @return {String} The GPU texture format.
  45885. */
  45886. getTextureFormatGPU( texture ) {
  45887. return this.backend.get( texture ).format;
  45888. }
  45889. /**
  45890. * Returns an object that defines the multi-sampling state of the given texture.
  45891. *
  45892. * @param {Texture} texture - The texture.
  45893. * @return {Object} The multi-sampling state.
  45894. */
  45895. getTextureSampleData( texture ) {
  45896. let samples;
  45897. if ( texture.isFramebufferTexture ) {
  45898. samples = 1;
  45899. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  45900. const renderer = this.backend.renderer;
  45901. const renderTarget = renderer.getRenderTarget();
  45902. samples = renderTarget ? renderTarget.samples : renderer.samples;
  45903. } else if ( texture.renderTarget ) {
  45904. samples = texture.renderTarget.samples;
  45905. }
  45906. samples = samples || 1;
  45907. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  45908. const primarySamples = isMSAA ? 1 : samples;
  45909. return { samples, primarySamples, isMSAA };
  45910. }
  45911. /**
  45912. * Returns the default color attachment's GPU format of the current render context.
  45913. *
  45914. * @param {RenderContext} renderContext - The render context.
  45915. * @return {String} The GPU texture format of the default color attachment.
  45916. */
  45917. getCurrentColorFormat( renderContext ) {
  45918. let format;
  45919. if ( renderContext.textures !== null ) {
  45920. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  45921. } else {
  45922. format = this.getPreferredCanvasFormat(); // default context format
  45923. }
  45924. return format;
  45925. }
  45926. /**
  45927. * Returns the output color space of the current render context.
  45928. *
  45929. * @param {RenderContext} renderContext - The render context.
  45930. * @return {String} The output color space.
  45931. */
  45932. getCurrentColorSpace( renderContext ) {
  45933. if ( renderContext.textures !== null ) {
  45934. return renderContext.textures[ 0 ].colorSpace;
  45935. }
  45936. return this.backend.renderer.outputColorSpace;
  45937. }
  45938. /**
  45939. * Returns GPU primitive topology for the given object and material.
  45940. *
  45941. * @param {Object3D} object - The 3D object.
  45942. * @param {Material} material - The material.
  45943. * @return {String} The GPU primitive topology.
  45944. */
  45945. getPrimitiveTopology( object, material ) {
  45946. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  45947. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  45948. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  45949. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  45950. }
  45951. /**
  45952. * Returns a modified sample count from the given sample count value.
  45953. *
  45954. * That is required since WebGPU does not support arbitrary sample counts.
  45955. *
  45956. * @param {Number} sampleCount - The input sample count.
  45957. * @return {Number} The (potentially updated) output sample count.
  45958. */
  45959. getSampleCount( sampleCount ) {
  45960. let count = 1;
  45961. if ( sampleCount > 1 ) {
  45962. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  45963. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  45964. if ( count === 2 ) {
  45965. count = 4;
  45966. }
  45967. }
  45968. return count;
  45969. }
  45970. /**
  45971. * Returns the sample count of the given render context.
  45972. *
  45973. * @param {RenderContext} renderContext - The render context.
  45974. * @return {Number} The sample count.
  45975. */
  45976. getSampleCountRenderContext( renderContext ) {
  45977. if ( renderContext.textures !== null ) {
  45978. return this.getSampleCount( renderContext.sampleCount );
  45979. }
  45980. return this.getSampleCount( this.backend.renderer.samples );
  45981. }
  45982. /**
  45983. * Returns the preferred canvas format.
  45984. *
  45985. * There is a separate method for this so it's possible to
  45986. * honor edge cases for specific devices.
  45987. *
  45988. * @return {String} The GPU texture format of the canvas.
  45989. */
  45990. getPreferredCanvasFormat() {
  45991. const outputType = this.backend.parameters.outputType;
  45992. if ( outputType === undefined ) {
  45993. return navigator.gpu.getPreferredCanvasFormat();
  45994. } else if ( outputType === UnsignedByteType ) {
  45995. return GPUTextureFormat.BGRA8Unorm;
  45996. } else if ( outputType === HalfFloatType ) {
  45997. return GPUTextureFormat.RGBA16Float;
  45998. } else {
  45999. throw new Error( 'Unsupported outputType' );
  46000. }
  46001. }
  46002. }
  46003. const typedArraysToVertexFormatPrefix = new Map( [
  46004. [ Int8Array, [ 'sint8', 'snorm8' ]],
  46005. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  46006. [ Int16Array, [ 'sint16', 'snorm16' ]],
  46007. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  46008. [ Int32Array, [ 'sint32', 'snorm32' ]],
  46009. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  46010. [ Float32Array, [ 'float32', ]],
  46011. ] );
  46012. const typedAttributeToVertexFormatPrefix = new Map( [
  46013. [ Float16BufferAttribute, [ 'float16', ]],
  46014. ] );
  46015. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  46016. [ Int32Array, 'sint32' ],
  46017. [ Int16Array, 'sint32' ], // patch for INT16
  46018. [ Uint32Array, 'uint32' ],
  46019. [ Uint16Array, 'uint32' ], // patch for UINT16
  46020. [ Float32Array, 'float32' ]
  46021. ] );
  46022. /**
  46023. * A WebGPU backend utility module for managing shader attributes.
  46024. *
  46025. * @private
  46026. */
  46027. class WebGPUAttributeUtils {
  46028. /**
  46029. * Constructs a new utility object.
  46030. *
  46031. * @param {WebGPUBackend} backend - The WebGPU backend.
  46032. */
  46033. constructor( backend ) {
  46034. /**
  46035. * A reference to the WebGPU backend.
  46036. *
  46037. * @type {WebGPUBackend}
  46038. */
  46039. this.backend = backend;
  46040. }
  46041. /**
  46042. * Creates the GPU buffer for the given buffer attribute.
  46043. *
  46044. * @param {BufferAttribute} attribute - The buffer attribute.
  46045. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  46046. */
  46047. createAttribute( attribute, usage ) {
  46048. const bufferAttribute = this._getBufferAttribute( attribute );
  46049. const backend = this.backend;
  46050. const bufferData = backend.get( bufferAttribute );
  46051. let buffer = bufferData.buffer;
  46052. if ( buffer === undefined ) {
  46053. const device = backend.device;
  46054. let array = bufferAttribute.array;
  46055. // patch for INT16 and UINT16
  46056. if ( attribute.normalized === false ) {
  46057. if ( array.constructor === Int16Array ) {
  46058. array = new Int32Array( array );
  46059. } else if ( array.constructor === Uint16Array ) {
  46060. array = new Uint32Array( array );
  46061. if ( usage & GPUBufferUsage.INDEX ) {
  46062. for ( let i = 0; i < array.length; i ++ ) {
  46063. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  46064. }
  46065. }
  46066. }
  46067. }
  46068. bufferAttribute.array = array;
  46069. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  46070. array = new array.constructor( bufferAttribute.count * 4 );
  46071. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  46072. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  46073. }
  46074. // Update BufferAttribute
  46075. bufferAttribute.itemSize = 4;
  46076. bufferAttribute.array = array;
  46077. }
  46078. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  46079. buffer = device.createBuffer( {
  46080. label: bufferAttribute.name,
  46081. size: size,
  46082. usage: usage,
  46083. mappedAtCreation: true
  46084. } );
  46085. new array.constructor( buffer.getMappedRange() ).set( array );
  46086. buffer.unmap();
  46087. bufferData.buffer = buffer;
  46088. }
  46089. }
  46090. /**
  46091. * Updates the GPU buffer of the given buffer attribute.
  46092. *
  46093. * @param {BufferAttribute} attribute - The buffer attribute.
  46094. */
  46095. updateAttribute( attribute ) {
  46096. const bufferAttribute = this._getBufferAttribute( attribute );
  46097. const backend = this.backend;
  46098. const device = backend.device;
  46099. const buffer = backend.get( bufferAttribute ).buffer;
  46100. const array = bufferAttribute.array;
  46101. const isTypedArray = this._isTypedArray( array );
  46102. const updateRanges = bufferAttribute.updateRanges;
  46103. if ( updateRanges.length === 0 ) {
  46104. // Not using update ranges
  46105. device.queue.writeBuffer(
  46106. buffer,
  46107. 0,
  46108. array,
  46109. 0
  46110. );
  46111. } else {
  46112. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  46113. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  46114. const range = updateRanges[ i ];
  46115. const dataOffset = range.start * byteOffsetFactor;
  46116. const size = range.count * byteOffsetFactor;
  46117. device.queue.writeBuffer(
  46118. buffer,
  46119. 0,
  46120. array,
  46121. dataOffset,
  46122. size
  46123. );
  46124. }
  46125. bufferAttribute.clearUpdateRanges();
  46126. }
  46127. }
  46128. /**
  46129. * This method creates the vertex buffer layout data which are
  46130. * require when creating a render pipeline for the given render object.
  46131. *
  46132. * @param {RenderObject} renderObject - The render object.
  46133. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  46134. */
  46135. createShaderVertexBuffers( renderObject ) {
  46136. const attributes = renderObject.getAttributes();
  46137. const vertexBuffers = new Map();
  46138. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  46139. const geometryAttribute = attributes[ slot ];
  46140. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  46141. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  46142. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  46143. if ( vertexBufferLayout === undefined ) {
  46144. let arrayStride, stepMode;
  46145. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  46146. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  46147. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  46148. } else {
  46149. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  46150. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  46151. }
  46152. // patch for INT16 and UINT16
  46153. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  46154. arrayStride = 4;
  46155. }
  46156. vertexBufferLayout = {
  46157. arrayStride,
  46158. attributes: [],
  46159. stepMode
  46160. };
  46161. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  46162. }
  46163. const format = this._getVertexFormat( geometryAttribute );
  46164. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  46165. vertexBufferLayout.attributes.push( {
  46166. shaderLocation: slot,
  46167. offset,
  46168. format
  46169. } );
  46170. }
  46171. return Array.from( vertexBuffers.values() );
  46172. }
  46173. /**
  46174. * Destroys the GPU buffer of the given buffer attribute.
  46175. *
  46176. * @param {BufferAttribute} attribute - The buffer attribute.
  46177. */
  46178. destroyAttribute( attribute ) {
  46179. const backend = this.backend;
  46180. const data = backend.get( this._getBufferAttribute( attribute ) );
  46181. data.buffer.destroy();
  46182. backend.delete( attribute );
  46183. }
  46184. /**
  46185. * This method performs a readback operation by moving buffer data from
  46186. * a storage buffer attribute from the GPU to the CPU.
  46187. *
  46188. * @async
  46189. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46190. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46191. */
  46192. async getArrayBufferAsync( attribute ) {
  46193. const backend = this.backend;
  46194. const device = backend.device;
  46195. const data = backend.get( this._getBufferAttribute( attribute ) );
  46196. const bufferGPU = data.buffer;
  46197. const size = bufferGPU.size;
  46198. const readBufferGPU = device.createBuffer( {
  46199. label: `${ attribute.name }_readback`,
  46200. size,
  46201. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46202. } );
  46203. const cmdEncoder = device.createCommandEncoder( {
  46204. label: `readback_encoder_${ attribute.name }`
  46205. } );
  46206. cmdEncoder.copyBufferToBuffer(
  46207. bufferGPU,
  46208. 0,
  46209. readBufferGPU,
  46210. 0,
  46211. size
  46212. );
  46213. const gpuCommands = cmdEncoder.finish();
  46214. device.queue.submit( [ gpuCommands ] );
  46215. await readBufferGPU.mapAsync( GPUMapMode.READ );
  46216. const arrayBuffer = readBufferGPU.getMappedRange();
  46217. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  46218. readBufferGPU.unmap();
  46219. return dstBuffer.buffer;
  46220. }
  46221. /**
  46222. * Returns the vertex format of the given buffer attribute.
  46223. *
  46224. * @private
  46225. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  46226. * @return {String} The vertex format (e.g. 'float32x3').
  46227. */
  46228. _getVertexFormat( geometryAttribute ) {
  46229. const { itemSize, normalized } = geometryAttribute;
  46230. const ArrayType = geometryAttribute.array.constructor;
  46231. const AttributeType = geometryAttribute.constructor;
  46232. let format;
  46233. if ( itemSize === 1 ) {
  46234. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  46235. } else {
  46236. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  46237. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  46238. if ( prefix ) {
  46239. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  46240. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  46241. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  46242. if ( paddedItemSize % 1 ) {
  46243. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  46244. }
  46245. format = `${prefix}x${paddedItemSize}`;
  46246. }
  46247. }
  46248. if ( ! format ) {
  46249. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  46250. }
  46251. return format;
  46252. }
  46253. /**
  46254. * Returns `true` if the given array is a typed array.
  46255. *
  46256. * @private
  46257. * @param {Any} array - The array.
  46258. * @return {Boolean} Whether the given array is a typed array or not.
  46259. */
  46260. _isTypedArray( array ) {
  46261. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  46262. }
  46263. /**
  46264. * Utility method for handling interleaved buffer attributes correctly.
  46265. * To process them, their `InterleavedBuffer` is returned.
  46266. *
  46267. * @private
  46268. * @param {BufferAttribute} attribute - The attribute.
  46269. * @return {BufferAttribute|InterleavedBuffer}
  46270. */
  46271. _getBufferAttribute( attribute ) {
  46272. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  46273. return attribute;
  46274. }
  46275. }
  46276. /**
  46277. * A WebGPU backend utility module for managing bindings.
  46278. *
  46279. * When reading the documentation it's helpful to keep in mind that
  46280. * all class definitions starting with 'GPU*' are modules from the
  46281. * WebGPU API. So for example `BindGroup` is a class from the engine
  46282. * whereas `GPUBindGroup` is a class from WebGPU.
  46283. *
  46284. * @private
  46285. */
  46286. class WebGPUBindingUtils {
  46287. /**
  46288. * Constructs a new utility object.
  46289. *
  46290. * @param {WebGPUBackend} backend - The WebGPU backend.
  46291. */
  46292. constructor( backend ) {
  46293. /**
  46294. * A reference to the WebGPU backend.
  46295. *
  46296. * @type {WebGPUBackend}
  46297. */
  46298. this.backend = backend;
  46299. /**
  46300. * A cache for managing bind group layouts.
  46301. *
  46302. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  46303. */
  46304. this.bindGroupLayoutCache = new WeakMap();
  46305. }
  46306. /**
  46307. * Creates a GPU bind group layout for the given bind group.
  46308. *
  46309. * @param {BindGroup} bindGroup - The bind group.
  46310. * @return {GPUBindGroupLayout} The GPU bind group layout.
  46311. */
  46312. createBindingsLayout( bindGroup ) {
  46313. const backend = this.backend;
  46314. const device = backend.device;
  46315. const entries = [];
  46316. let index = 0;
  46317. for ( const binding of bindGroup.bindings ) {
  46318. const bindingGPU = {
  46319. binding: index ++,
  46320. visibility: binding.visibility
  46321. };
  46322. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  46323. const buffer = {}; // GPUBufferBindingLayout
  46324. if ( binding.isStorageBuffer ) {
  46325. if ( binding.visibility & 4 ) {
  46326. // compute
  46327. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  46328. buffer.type = GPUBufferBindingType.Storage;
  46329. } else {
  46330. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  46331. }
  46332. } else {
  46333. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  46334. }
  46335. }
  46336. bindingGPU.buffer = buffer;
  46337. } else if ( binding.isSampler ) {
  46338. const sampler = {}; // GPUSamplerBindingLayout
  46339. if ( binding.texture.isDepthTexture ) {
  46340. if ( binding.texture.compareFunction !== null ) {
  46341. sampler.type = 'comparison';
  46342. }
  46343. }
  46344. bindingGPU.sampler = sampler;
  46345. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  46346. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  46347. } else if ( binding.isSampledTexture && binding.store ) {
  46348. const storageTexture = {}; // GPUStorageTextureBindingLayout
  46349. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  46350. const access = binding.access;
  46351. if ( access === NodeAccess.READ_WRITE ) {
  46352. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  46353. } else if ( access === NodeAccess.WRITE_ONLY ) {
  46354. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  46355. } else {
  46356. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  46357. }
  46358. bindingGPU.storageTexture = storageTexture;
  46359. } else if ( binding.isSampledTexture ) {
  46360. const texture = {}; // GPUTextureBindingLayout
  46361. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  46362. if ( primarySamples > 1 ) {
  46363. texture.multisampled = true;
  46364. if ( ! binding.texture.isDepthTexture ) {
  46365. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46366. }
  46367. }
  46368. if ( binding.texture.isDepthTexture ) {
  46369. texture.sampleType = GPUTextureSampleType.Depth;
  46370. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  46371. const type = binding.texture.type;
  46372. if ( type === IntType ) {
  46373. texture.sampleType = GPUTextureSampleType.SInt;
  46374. } else if ( type === UnsignedIntType ) {
  46375. texture.sampleType = GPUTextureSampleType.UInt;
  46376. } else if ( type === FloatType ) {
  46377. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  46378. texture.sampleType = GPUTextureSampleType.Float;
  46379. } else {
  46380. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  46381. }
  46382. }
  46383. }
  46384. if ( binding.isSampledCubeTexture ) {
  46385. texture.viewDimension = GPUTextureViewDimension.Cube;
  46386. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46387. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  46388. } else if ( binding.isSampledTexture3D ) {
  46389. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  46390. }
  46391. bindingGPU.texture = texture;
  46392. } else {
  46393. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  46394. }
  46395. entries.push( bindingGPU );
  46396. }
  46397. return device.createBindGroupLayout( { entries } );
  46398. }
  46399. /**
  46400. * Creates bindings from the given bind group definition.
  46401. *
  46402. * @param {BindGroup} bindGroup - The bind group.
  46403. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46404. * @param {Number} cacheIndex - The cache index.
  46405. * @param {Number} version - The version.
  46406. */
  46407. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  46408. const { backend, bindGroupLayoutCache } = this;
  46409. const bindingsData = backend.get( bindGroup );
  46410. // setup (static) binding layout and (dynamic) binding group
  46411. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  46412. if ( bindLayoutGPU === undefined ) {
  46413. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  46414. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  46415. }
  46416. let bindGroupGPU;
  46417. if ( cacheIndex > 0 ) {
  46418. if ( bindingsData.groups === undefined ) {
  46419. bindingsData.groups = [];
  46420. bindingsData.versions = [];
  46421. }
  46422. if ( bindingsData.versions[ cacheIndex ] === version ) {
  46423. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  46424. }
  46425. }
  46426. if ( bindGroupGPU === undefined ) {
  46427. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  46428. if ( cacheIndex > 0 ) {
  46429. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  46430. bindingsData.versions[ cacheIndex ] = version;
  46431. }
  46432. }
  46433. bindingsData.group = bindGroupGPU;
  46434. bindingsData.layout = bindLayoutGPU;
  46435. }
  46436. /**
  46437. * Updates a buffer binding.
  46438. *
  46439. * @param {Buffer} binding - The buffer binding to update.
  46440. */
  46441. updateBinding( binding ) {
  46442. const backend = this.backend;
  46443. const device = backend.device;
  46444. const buffer = binding.buffer;
  46445. const bufferGPU = backend.get( binding ).buffer;
  46446. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  46447. }
  46448. /**
  46449. * Creates a GPU bind group for the camera index.
  46450. *
  46451. * @param {Uint32Array} data - The index data.
  46452. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  46453. * @return {GPUBindGroup} The GPU bind group.
  46454. */
  46455. createBindGroupIndex( data, layout ) {
  46456. const backend = this.backend;
  46457. const device = backend.device;
  46458. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46459. const index = data[ 0 ];
  46460. const buffer = device.createBuffer( {
  46461. label: 'bindingCameraIndex_' + index,
  46462. size: 16, // uint(4) * 4
  46463. usage: usage
  46464. } );
  46465. device.queue.writeBuffer( buffer, 0, data, 0 );
  46466. const entries = [ { binding: 0, resource: { buffer } } ];
  46467. return device.createBindGroup( {
  46468. label: 'bindGroupCameraIndex_' + index,
  46469. layout,
  46470. entries
  46471. } );
  46472. }
  46473. /**
  46474. * Creates a GPU bind group for the given bind group and GPU layout.
  46475. *
  46476. * @param {BindGroup} bindGroup - The bind group.
  46477. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  46478. * @return {GPUBindGroup} The GPU bind group.
  46479. */
  46480. createBindGroup( bindGroup, layoutGPU ) {
  46481. const backend = this.backend;
  46482. const device = backend.device;
  46483. let bindingPoint = 0;
  46484. const entriesGPU = [];
  46485. for ( const binding of bindGroup.bindings ) {
  46486. if ( binding.isUniformBuffer ) {
  46487. const bindingData = backend.get( binding );
  46488. if ( bindingData.buffer === undefined ) {
  46489. const byteLength = binding.byteLength;
  46490. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  46491. const bufferGPU = device.createBuffer( {
  46492. label: 'bindingBuffer_' + binding.name,
  46493. size: byteLength,
  46494. usage: usage
  46495. } );
  46496. bindingData.buffer = bufferGPU;
  46497. }
  46498. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46499. } else if ( binding.isStorageBuffer ) {
  46500. const bindingData = backend.get( binding );
  46501. if ( bindingData.buffer === undefined ) {
  46502. const attribute = binding.attribute;
  46503. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  46504. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  46505. bindingData.buffer = backend.get( attribute ).buffer;
  46506. }
  46507. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  46508. } else if ( binding.isSampler ) {
  46509. const textureGPU = backend.get( binding.texture );
  46510. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  46511. } else if ( binding.isSampledTexture ) {
  46512. const textureData = backend.get( binding.texture );
  46513. let resourceGPU;
  46514. if ( textureData.externalTexture !== undefined ) {
  46515. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  46516. } else {
  46517. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  46518. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  46519. resourceGPU = textureData[ propertyName ];
  46520. if ( resourceGPU === undefined ) {
  46521. const aspectGPU = GPUTextureAspect.All;
  46522. let dimensionViewGPU;
  46523. if ( binding.isSampledCubeTexture ) {
  46524. dimensionViewGPU = GPUTextureViewDimension.Cube;
  46525. } else if ( binding.isSampledTexture3D ) {
  46526. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  46527. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  46528. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  46529. } else {
  46530. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  46531. }
  46532. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  46533. }
  46534. }
  46535. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  46536. }
  46537. bindingPoint ++;
  46538. }
  46539. return device.createBindGroup( {
  46540. label: 'bindGroup_' + bindGroup.name,
  46541. layout: layoutGPU,
  46542. entries: entriesGPU
  46543. } );
  46544. }
  46545. }
  46546. /**
  46547. * A WebGPU backend utility module for managing pipelines.
  46548. *
  46549. * @private
  46550. */
  46551. class WebGPUPipelineUtils {
  46552. /**
  46553. * Constructs a new utility object.
  46554. *
  46555. * @param {WebGPUBackend} backend - The WebGPU backend.
  46556. */
  46557. constructor( backend ) {
  46558. /**
  46559. * A reference to the WebGPU backend.
  46560. *
  46561. * @type {WebGPUBackend}
  46562. */
  46563. this.backend = backend;
  46564. }
  46565. /**
  46566. * Returns the sample count derived from the given render context.
  46567. *
  46568. * @private
  46569. * @param {RenderContext} renderContext - The render context.
  46570. * @return {Number} The sample count.
  46571. */
  46572. _getSampleCount( renderContext ) {
  46573. return this.backend.utils.getSampleCountRenderContext( renderContext );
  46574. }
  46575. /**
  46576. * Creates a render pipeline for the given render object.
  46577. *
  46578. * @param {RenderObject} renderObject - The render object.
  46579. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46580. */
  46581. createRenderPipeline( renderObject, promises ) {
  46582. const { object, material, geometry, pipeline } = renderObject;
  46583. const { vertexProgram, fragmentProgram } = pipeline;
  46584. const backend = this.backend;
  46585. const device = backend.device;
  46586. const utils = backend.utils;
  46587. const pipelineData = backend.get( pipeline );
  46588. // bind group layouts
  46589. const bindGroupLayouts = [];
  46590. for ( const bindGroup of renderObject.getBindings() ) {
  46591. const bindingsData = backend.get( bindGroup );
  46592. bindGroupLayouts.push( bindingsData.layout );
  46593. }
  46594. // vertex buffers
  46595. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  46596. // blending
  46597. let blending;
  46598. if ( material.transparent === true && material.blending !== NoBlending ) {
  46599. blending = this._getBlending( material );
  46600. }
  46601. // stencil
  46602. let stencilFront = {};
  46603. if ( material.stencilWrite === true ) {
  46604. stencilFront = {
  46605. compare: this._getStencilCompare( material ),
  46606. failOp: this._getStencilOperation( material.stencilFail ),
  46607. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  46608. passOp: this._getStencilOperation( material.stencilZPass )
  46609. };
  46610. }
  46611. const colorWriteMask = this._getColorWriteMask( material );
  46612. const targets = [];
  46613. if ( renderObject.context.textures !== null ) {
  46614. const textures = renderObject.context.textures;
  46615. for ( let i = 0; i < textures.length; i ++ ) {
  46616. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  46617. targets.push( {
  46618. format: colorFormat,
  46619. blend: blending,
  46620. writeMask: colorWriteMask
  46621. } );
  46622. }
  46623. } else {
  46624. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  46625. targets.push( {
  46626. format: colorFormat,
  46627. blend: blending,
  46628. writeMask: colorWriteMask
  46629. } );
  46630. }
  46631. const vertexModule = backend.get( vertexProgram ).module;
  46632. const fragmentModule = backend.get( fragmentProgram ).module;
  46633. const primitiveState = this._getPrimitiveState( object, geometry, material );
  46634. const depthCompare = this._getDepthCompare( material );
  46635. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  46636. const sampleCount = this._getSampleCount( renderObject.context );
  46637. const pipelineDescriptor = {
  46638. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  46639. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  46640. fragment: Object.assign( {}, fragmentModule, { targets } ),
  46641. primitive: primitiveState,
  46642. multisample: {
  46643. count: sampleCount,
  46644. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  46645. },
  46646. layout: device.createPipelineLayout( {
  46647. bindGroupLayouts
  46648. } )
  46649. };
  46650. const depthStencil = {};
  46651. const renderDepth = renderObject.context.depth;
  46652. const renderStencil = renderObject.context.stencil;
  46653. if ( renderDepth === true || renderStencil === true ) {
  46654. if ( renderDepth === true ) {
  46655. depthStencil.format = depthStencilFormat;
  46656. depthStencil.depthWriteEnabled = material.depthWrite;
  46657. depthStencil.depthCompare = depthCompare;
  46658. }
  46659. if ( renderStencil === true ) {
  46660. depthStencil.stencilFront = stencilFront;
  46661. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  46662. depthStencil.stencilReadMask = material.stencilFuncMask;
  46663. depthStencil.stencilWriteMask = material.stencilWriteMask;
  46664. }
  46665. pipelineDescriptor.depthStencil = depthStencil;
  46666. }
  46667. if ( promises === null ) {
  46668. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  46669. } else {
  46670. const p = new Promise( ( resolve /*, reject*/ ) => {
  46671. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  46672. pipelineData.pipeline = pipeline;
  46673. resolve();
  46674. } );
  46675. } );
  46676. promises.push( p );
  46677. }
  46678. }
  46679. /**
  46680. * Creates GPU render bundle encoder for the given render context.
  46681. *
  46682. * @param {RenderContext} renderContext - The render context.
  46683. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  46684. */
  46685. createBundleEncoder( renderContext ) {
  46686. const backend = this.backend;
  46687. const { utils, device } = backend;
  46688. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  46689. const colorFormat = utils.getCurrentColorFormat( renderContext );
  46690. const sampleCount = this._getSampleCount( renderContext );
  46691. const descriptor = {
  46692. label: 'renderBundleEncoder',
  46693. colorFormats: [ colorFormat ],
  46694. depthStencilFormat,
  46695. sampleCount
  46696. };
  46697. return device.createRenderBundleEncoder( descriptor );
  46698. }
  46699. /**
  46700. * Creates a compute pipeline for the given compute node.
  46701. *
  46702. * @param {ComputePipeline} pipeline - The compute pipeline.
  46703. * @param {Array<BindGroup>} bindings - The bindings.
  46704. */
  46705. createComputePipeline( pipeline, bindings ) {
  46706. const backend = this.backend;
  46707. const device = backend.device;
  46708. const computeProgram = backend.get( pipeline.computeProgram ).module;
  46709. const pipelineGPU = backend.get( pipeline );
  46710. // bind group layouts
  46711. const bindGroupLayouts = [];
  46712. for ( const bindingsGroup of bindings ) {
  46713. const bindingsData = backend.get( bindingsGroup );
  46714. bindGroupLayouts.push( bindingsData.layout );
  46715. }
  46716. pipelineGPU.pipeline = device.createComputePipeline( {
  46717. compute: computeProgram,
  46718. layout: device.createPipelineLayout( {
  46719. bindGroupLayouts
  46720. } )
  46721. } );
  46722. }
  46723. /**
  46724. * Returns the blending state as a descriptor object required
  46725. * for the pipeline creation.
  46726. *
  46727. * @private
  46728. * @param {Material} material - The material.
  46729. * @return {Object} The blending state.
  46730. */
  46731. _getBlending( material ) {
  46732. let color, alpha;
  46733. const blending = material.blending;
  46734. const blendSrc = material.blendSrc;
  46735. const blendDst = material.blendDst;
  46736. const blendEquation = material.blendEquation;
  46737. if ( blending === CustomBlending ) {
  46738. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  46739. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  46740. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  46741. color = {
  46742. srcFactor: this._getBlendFactor( blendSrc ),
  46743. dstFactor: this._getBlendFactor( blendDst ),
  46744. operation: this._getBlendOperation( blendEquation )
  46745. };
  46746. alpha = {
  46747. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  46748. dstFactor: this._getBlendFactor( blendDstAlpha ),
  46749. operation: this._getBlendOperation( blendEquationAlpha )
  46750. };
  46751. } else {
  46752. const premultipliedAlpha = material.premultipliedAlpha;
  46753. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  46754. color = {
  46755. srcFactor: srcRGB,
  46756. dstFactor: dstRGB,
  46757. operation: GPUBlendOperation.Add
  46758. };
  46759. alpha = {
  46760. srcFactor: srcAlpha,
  46761. dstFactor: dstAlpha,
  46762. operation: GPUBlendOperation.Add
  46763. };
  46764. };
  46765. if ( premultipliedAlpha ) {
  46766. switch ( blending ) {
  46767. case NormalBlending:
  46768. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  46769. break;
  46770. case AdditiveBlending:
  46771. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  46772. break;
  46773. case SubtractiveBlending:
  46774. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  46775. break;
  46776. case MultiplyBlending:
  46777. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  46778. break;
  46779. }
  46780. } else {
  46781. switch ( blending ) {
  46782. case NormalBlending:
  46783. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  46784. break;
  46785. case AdditiveBlending:
  46786. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  46787. break;
  46788. case SubtractiveBlending:
  46789. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  46790. break;
  46791. case MultiplyBlending:
  46792. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  46793. break;
  46794. }
  46795. }
  46796. }
  46797. if ( color !== undefined && alpha !== undefined ) {
  46798. return { color, alpha };
  46799. } else {
  46800. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  46801. }
  46802. }
  46803. /**
  46804. * Returns the GPU blend factor which is required for the pipeline creation.
  46805. *
  46806. * @private
  46807. * @param {Number} blend - The blend factor as a three.js constant.
  46808. * @return {String} The GPU blend factor.
  46809. */
  46810. _getBlendFactor( blend ) {
  46811. let blendFactor;
  46812. switch ( blend ) {
  46813. case ZeroFactor:
  46814. blendFactor = GPUBlendFactor.Zero;
  46815. break;
  46816. case OneFactor:
  46817. blendFactor = GPUBlendFactor.One;
  46818. break;
  46819. case SrcColorFactor:
  46820. blendFactor = GPUBlendFactor.Src;
  46821. break;
  46822. case OneMinusSrcColorFactor:
  46823. blendFactor = GPUBlendFactor.OneMinusSrc;
  46824. break;
  46825. case SrcAlphaFactor:
  46826. blendFactor = GPUBlendFactor.SrcAlpha;
  46827. break;
  46828. case OneMinusSrcAlphaFactor:
  46829. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  46830. break;
  46831. case DstColorFactor:
  46832. blendFactor = GPUBlendFactor.Dst;
  46833. break;
  46834. case OneMinusDstColorFactor:
  46835. blendFactor = GPUBlendFactor.OneMinusDstColor;
  46836. break;
  46837. case DstAlphaFactor:
  46838. blendFactor = GPUBlendFactor.DstAlpha;
  46839. break;
  46840. case OneMinusDstAlphaFactor:
  46841. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  46842. break;
  46843. case SrcAlphaSaturateFactor:
  46844. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  46845. break;
  46846. case BlendColorFactor:
  46847. blendFactor = GPUBlendFactor.Constant;
  46848. break;
  46849. case OneMinusBlendColorFactor:
  46850. blendFactor = GPUBlendFactor.OneMinusConstant;
  46851. break;
  46852. default:
  46853. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  46854. }
  46855. return blendFactor;
  46856. }
  46857. /**
  46858. * Returns the GPU stencil compare function which is required for the pipeline creation.
  46859. *
  46860. * @private
  46861. * @param {Material} material - The material.
  46862. * @return {String} The GPU stencil compare function.
  46863. */
  46864. _getStencilCompare( material ) {
  46865. let stencilCompare;
  46866. const stencilFunc = material.stencilFunc;
  46867. switch ( stencilFunc ) {
  46868. case NeverStencilFunc:
  46869. stencilCompare = GPUCompareFunction.Never;
  46870. break;
  46871. case AlwaysStencilFunc:
  46872. stencilCompare = GPUCompareFunction.Always;
  46873. break;
  46874. case LessStencilFunc:
  46875. stencilCompare = GPUCompareFunction.Less;
  46876. break;
  46877. case LessEqualStencilFunc:
  46878. stencilCompare = GPUCompareFunction.LessEqual;
  46879. break;
  46880. case EqualStencilFunc:
  46881. stencilCompare = GPUCompareFunction.Equal;
  46882. break;
  46883. case GreaterEqualStencilFunc:
  46884. stencilCompare = GPUCompareFunction.GreaterEqual;
  46885. break;
  46886. case GreaterStencilFunc:
  46887. stencilCompare = GPUCompareFunction.Greater;
  46888. break;
  46889. case NotEqualStencilFunc:
  46890. stencilCompare = GPUCompareFunction.NotEqual;
  46891. break;
  46892. default:
  46893. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  46894. }
  46895. return stencilCompare;
  46896. }
  46897. /**
  46898. * Returns the GPU stencil operation which is required for the pipeline creation.
  46899. *
  46900. * @private
  46901. * @param {Number} op - A three.js constant defining the stencil operation.
  46902. * @return {String} The GPU stencil operation.
  46903. */
  46904. _getStencilOperation( op ) {
  46905. let stencilOperation;
  46906. switch ( op ) {
  46907. case KeepStencilOp:
  46908. stencilOperation = GPUStencilOperation.Keep;
  46909. break;
  46910. case ZeroStencilOp:
  46911. stencilOperation = GPUStencilOperation.Zero;
  46912. break;
  46913. case ReplaceStencilOp:
  46914. stencilOperation = GPUStencilOperation.Replace;
  46915. break;
  46916. case InvertStencilOp:
  46917. stencilOperation = GPUStencilOperation.Invert;
  46918. break;
  46919. case IncrementStencilOp:
  46920. stencilOperation = GPUStencilOperation.IncrementClamp;
  46921. break;
  46922. case DecrementStencilOp:
  46923. stencilOperation = GPUStencilOperation.DecrementClamp;
  46924. break;
  46925. case IncrementWrapStencilOp:
  46926. stencilOperation = GPUStencilOperation.IncrementWrap;
  46927. break;
  46928. case DecrementWrapStencilOp:
  46929. stencilOperation = GPUStencilOperation.DecrementWrap;
  46930. break;
  46931. default:
  46932. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  46933. }
  46934. return stencilOperation;
  46935. }
  46936. /**
  46937. * Returns the GPU blend operation which is required for the pipeline creation.
  46938. *
  46939. * @private
  46940. * @param {Number} blendEquation - A three.js constant defining the blend equation.
  46941. * @return {String} The GPU blend operation.
  46942. */
  46943. _getBlendOperation( blendEquation ) {
  46944. let blendOperation;
  46945. switch ( blendEquation ) {
  46946. case AddEquation:
  46947. blendOperation = GPUBlendOperation.Add;
  46948. break;
  46949. case SubtractEquation:
  46950. blendOperation = GPUBlendOperation.Subtract;
  46951. break;
  46952. case ReverseSubtractEquation:
  46953. blendOperation = GPUBlendOperation.ReverseSubtract;
  46954. break;
  46955. case MinEquation:
  46956. blendOperation = GPUBlendOperation.Min;
  46957. break;
  46958. case MaxEquation:
  46959. blendOperation = GPUBlendOperation.Max;
  46960. break;
  46961. default:
  46962. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  46963. }
  46964. return blendOperation;
  46965. }
  46966. /**
  46967. * Returns the primitive state as a descriptor object required
  46968. * for the pipeline creation.
  46969. *
  46970. * @private
  46971. * @param {Object3D} object - The 3D object.
  46972. * @param {BufferGeometry} geometry - The geometry.
  46973. * @param {Material} material - The material.
  46974. * @return {Object} The primitive state.
  46975. */
  46976. _getPrimitiveState( object, geometry, material ) {
  46977. const descriptor = {};
  46978. const utils = this.backend.utils;
  46979. descriptor.topology = utils.getPrimitiveTopology( object, material );
  46980. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  46981. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  46982. }
  46983. switch ( material.side ) {
  46984. case FrontSide:
  46985. descriptor.frontFace = GPUFrontFace.CCW;
  46986. descriptor.cullMode = GPUCullMode.Back;
  46987. break;
  46988. case BackSide:
  46989. descriptor.frontFace = GPUFrontFace.CCW;
  46990. descriptor.cullMode = GPUCullMode.Front;
  46991. break;
  46992. case DoubleSide:
  46993. descriptor.frontFace = GPUFrontFace.CCW;
  46994. descriptor.cullMode = GPUCullMode.None;
  46995. break;
  46996. default:
  46997. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  46998. break;
  46999. }
  47000. return descriptor;
  47001. }
  47002. /**
  47003. * Returns the GPU color write mask which is required for the pipeline creation.
  47004. *
  47005. * @private
  47006. * @param {Material} material - The material.
  47007. * @return {String} The GPU color write mask.
  47008. */
  47009. _getColorWriteMask( material ) {
  47010. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  47011. }
  47012. /**
  47013. * Returns the GPU depth compare function which is required for the pipeline creation.
  47014. *
  47015. * @private
  47016. * @param {Material} material - The material.
  47017. * @return {String} The GPU depth compare function.
  47018. */
  47019. _getDepthCompare( material ) {
  47020. let depthCompare;
  47021. if ( material.depthTest === false ) {
  47022. depthCompare = GPUCompareFunction.Always;
  47023. } else {
  47024. const depthFunc = material.depthFunc;
  47025. switch ( depthFunc ) {
  47026. case NeverDepth:
  47027. depthCompare = GPUCompareFunction.Never;
  47028. break;
  47029. case AlwaysDepth:
  47030. depthCompare = GPUCompareFunction.Always;
  47031. break;
  47032. case LessDepth:
  47033. depthCompare = GPUCompareFunction.Less;
  47034. break;
  47035. case LessEqualDepth:
  47036. depthCompare = GPUCompareFunction.LessEqual;
  47037. break;
  47038. case EqualDepth:
  47039. depthCompare = GPUCompareFunction.Equal;
  47040. break;
  47041. case GreaterEqualDepth:
  47042. depthCompare = GPUCompareFunction.GreaterEqual;
  47043. break;
  47044. case GreaterDepth:
  47045. depthCompare = GPUCompareFunction.Greater;
  47046. break;
  47047. case NotEqualDepth:
  47048. depthCompare = GPUCompareFunction.NotEqual;
  47049. break;
  47050. default:
  47051. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  47052. }
  47053. }
  47054. return depthCompare;
  47055. }
  47056. }
  47057. /**
  47058. * Manages a pool of WebGPU timestamp queries for performance measurement.
  47059. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  47060. * @extends TimestampQueryPool
  47061. */
  47062. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  47063. /**
  47064. * Creates a new WebGPU timestamp query pool.
  47065. * @param {GPUDevice} device - The WebGPU device to create queries on.
  47066. * @param {string} type - The type identifier for this query pool.
  47067. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  47068. */
  47069. constructor( device, type, maxQueries = 2048 ) {
  47070. super( maxQueries );
  47071. this.device = device;
  47072. this.type = type;
  47073. this.querySet = this.device.createQuerySet( {
  47074. type: 'timestamp',
  47075. count: this.maxQueries,
  47076. label: `queryset_global_timestamp_${type}`
  47077. } );
  47078. const bufferSize = this.maxQueries * 8;
  47079. this.resolveBuffer = this.device.createBuffer( {
  47080. label: `buffer_timestamp_resolve_${type}`,
  47081. size: bufferSize,
  47082. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  47083. } );
  47084. this.resultBuffer = this.device.createBuffer( {
  47085. label: `buffer_timestamp_result_${type}`,
  47086. size: bufferSize,
  47087. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47088. } );
  47089. }
  47090. /**
  47091. * Allocates a pair of queries for a given render context.
  47092. * @param {Object} renderContext - The render context to allocate queries for.
  47093. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  47094. */
  47095. allocateQueriesForContext( renderContext ) {
  47096. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  47097. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  47098. 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() } ).` );
  47099. return null;
  47100. }
  47101. const baseOffset = this.currentQueryIndex;
  47102. this.currentQueryIndex += 2;
  47103. this.queryOffsets.set( renderContext.id, baseOffset );
  47104. return baseOffset;
  47105. }
  47106. /**
  47107. * Asynchronously resolves all pending queries and returns the total duration.
  47108. * If there's already a pending resolve operation, returns that promise instead.
  47109. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  47110. */
  47111. async resolveQueriesAsync() {
  47112. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  47113. return this.lastValue;
  47114. }
  47115. if ( this.pendingResolve ) {
  47116. return this.pendingResolve;
  47117. }
  47118. this.pendingResolve = this._resolveQueries();
  47119. try {
  47120. const result = await this.pendingResolve;
  47121. return result;
  47122. } finally {
  47123. this.pendingResolve = null;
  47124. }
  47125. }
  47126. /**
  47127. * Internal method to resolve queries and calculate total duration.
  47128. * @private
  47129. * @returns {Promise<number>} The total duration in milliseconds.
  47130. */
  47131. async _resolveQueries() {
  47132. if ( this.isDisposed ) {
  47133. return this.lastValue;
  47134. }
  47135. try {
  47136. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  47137. return this.lastValue;
  47138. }
  47139. const currentOffsets = new Map( this.queryOffsets );
  47140. const queryCount = this.currentQueryIndex;
  47141. const bytesUsed = queryCount * 8;
  47142. // Reset state before GPU work
  47143. this.currentQueryIndex = 0;
  47144. this.queryOffsets.clear();
  47145. const commandEncoder = this.device.createCommandEncoder();
  47146. commandEncoder.resolveQuerySet(
  47147. this.querySet,
  47148. 0,
  47149. queryCount,
  47150. this.resolveBuffer,
  47151. 0
  47152. );
  47153. commandEncoder.copyBufferToBuffer(
  47154. this.resolveBuffer,
  47155. 0,
  47156. this.resultBuffer,
  47157. 0,
  47158. bytesUsed
  47159. );
  47160. const commandBuffer = commandEncoder.finish();
  47161. this.device.queue.submit( [ commandBuffer ] );
  47162. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  47163. return this.lastValue;
  47164. }
  47165. // Create and track the mapping operation
  47166. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  47167. if ( this.isDisposed ) {
  47168. if ( this.resultBuffer.mapState === 'mapped' ) {
  47169. this.resultBuffer.unmap();
  47170. }
  47171. return this.lastValue;
  47172. }
  47173. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  47174. let totalDuration = 0;
  47175. for ( const [ , baseOffset ] of currentOffsets ) {
  47176. const startTime = times[ baseOffset ];
  47177. const endTime = times[ baseOffset + 1 ];
  47178. const duration = Number( endTime - startTime ) / 1e6;
  47179. totalDuration += duration;
  47180. }
  47181. this.resultBuffer.unmap();
  47182. this.lastValue = totalDuration;
  47183. return totalDuration;
  47184. } catch ( error ) {
  47185. console.error( 'Error resolving queries:', error );
  47186. if ( this.resultBuffer.mapState === 'mapped' ) {
  47187. this.resultBuffer.unmap();
  47188. }
  47189. return this.lastValue;
  47190. }
  47191. }
  47192. async dispose() {
  47193. if ( this.isDisposed ) {
  47194. return;
  47195. }
  47196. this.isDisposed = true;
  47197. // Wait for pending resolve operation
  47198. if ( this.pendingResolve ) {
  47199. try {
  47200. await this.pendingResolve;
  47201. } catch ( error ) {
  47202. console.error( 'Error waiting for pending resolve:', error );
  47203. }
  47204. }
  47205. // Ensure buffer is unmapped before destroying
  47206. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  47207. try {
  47208. this.resultBuffer.unmap();
  47209. } catch ( error ) {
  47210. console.error( 'Error unmapping buffer:', error );
  47211. }
  47212. }
  47213. // Destroy resources
  47214. if ( this.querySet ) {
  47215. this.querySet.destroy();
  47216. this.querySet = null;
  47217. }
  47218. if ( this.resolveBuffer ) {
  47219. this.resolveBuffer.destroy();
  47220. this.resolveBuffer = null;
  47221. }
  47222. if ( this.resultBuffer ) {
  47223. this.resultBuffer.destroy();
  47224. this.resultBuffer = null;
  47225. }
  47226. this.queryOffsets.clear();
  47227. this.pendingResolve = null;
  47228. }
  47229. }
  47230. /*// debugger tools
  47231. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  47232. //*/
  47233. /**
  47234. * A backend implementation targeting WebGPU.
  47235. *
  47236. * @private
  47237. * @augments Backend
  47238. */
  47239. class WebGPUBackend extends Backend {
  47240. /**
  47241. * Constructs a new WebGPU backend.
  47242. *
  47243. * @param {Object} parameters - The configuration parameter.
  47244. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  47245. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  47246. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  47247. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  47248. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  47249. * @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.
  47250. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  47251. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  47252. * @param {String} [parameters.powerPreference=undefined] - The power preference.
  47253. * @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.
  47254. * @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.
  47255. * @param {Number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  47256. */
  47257. constructor( parameters = {} ) {
  47258. super( parameters );
  47259. /**
  47260. * This flag can be used for type testing.
  47261. *
  47262. * @type {Boolean}
  47263. * @readonly
  47264. * @default true
  47265. */
  47266. this.isWebGPUBackend = true;
  47267. // some parameters require default values other than "undefined"
  47268. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  47269. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  47270. /**
  47271. * Whether to track timestamps with a Timestamp Query API or not.
  47272. *
  47273. * @type {Boolean}
  47274. * @default false
  47275. */
  47276. this.trackTimestamp = ( parameters.trackTimestamp === true );
  47277. /**
  47278. * A reference to the device.
  47279. *
  47280. * @type {GPUDevice?}
  47281. * @default null
  47282. */
  47283. this.device = null;
  47284. /**
  47285. * A reference to the context.
  47286. *
  47287. * @type {GPUCanvasContext?}
  47288. * @default null
  47289. */
  47290. this.context = null;
  47291. /**
  47292. * A reference to the color attachment of the default framebuffer.
  47293. *
  47294. * @type {GPUTexture?}
  47295. * @default null
  47296. */
  47297. this.colorBuffer = null;
  47298. /**
  47299. * A reference to the default render pass descriptor.
  47300. *
  47301. * @type {Object?}
  47302. * @default null
  47303. */
  47304. this.defaultRenderPassdescriptor = null;
  47305. /**
  47306. * A reference to a backend module holding common utility functions.
  47307. *
  47308. * @type {WebGPUUtils}
  47309. */
  47310. this.utils = new WebGPUUtils( this );
  47311. /**
  47312. * A reference to a backend module holding shader attribute-related
  47313. * utility functions.
  47314. *
  47315. * @type {WebGPUAttributeUtils}
  47316. */
  47317. this.attributeUtils = new WebGPUAttributeUtils( this );
  47318. /**
  47319. * A reference to a backend module holding shader binding-related
  47320. * utility functions.
  47321. *
  47322. * @type {WebGPUBindingUtils}
  47323. */
  47324. this.bindingUtils = new WebGPUBindingUtils( this );
  47325. /**
  47326. * A reference to a backend module holding shader pipeline-related
  47327. * utility functions.
  47328. *
  47329. * @type {WebGPUPipelineUtils}
  47330. */
  47331. this.pipelineUtils = new WebGPUPipelineUtils( this );
  47332. /**
  47333. * A reference to a backend module holding shader texture-related
  47334. * utility functions.
  47335. *
  47336. * @type {WebGPUTextureUtils}
  47337. */
  47338. this.textureUtils = new WebGPUTextureUtils( this );
  47339. /**
  47340. * A map that manages the resolve buffers for occlusion queries.
  47341. *
  47342. * @type {Map<Number,GPUBuffer>}
  47343. */
  47344. this.occludedResolveCache = new Map();
  47345. }
  47346. /**
  47347. * Initializes the backend so it is ready for usage.
  47348. *
  47349. * @async
  47350. * @param {Renderer} renderer - The renderer.
  47351. * @return {Promise} A Promise that resolves when the backend has been initialized.
  47352. */
  47353. async init( renderer ) {
  47354. await super.init( renderer );
  47355. //
  47356. const parameters = this.parameters;
  47357. // create the device if it is not passed with parameters
  47358. let device;
  47359. if ( parameters.device === undefined ) {
  47360. const adapterOptions = {
  47361. powerPreference: parameters.powerPreference
  47362. };
  47363. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  47364. if ( adapter === null ) {
  47365. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  47366. }
  47367. // feature support
  47368. const features = Object.values( GPUFeatureName );
  47369. const supportedFeatures = [];
  47370. for ( const name of features ) {
  47371. if ( adapter.features.has( name ) ) {
  47372. supportedFeatures.push( name );
  47373. }
  47374. }
  47375. const deviceDescriptor = {
  47376. requiredFeatures: supportedFeatures,
  47377. requiredLimits: parameters.requiredLimits
  47378. };
  47379. device = await adapter.requestDevice( deviceDescriptor );
  47380. } else {
  47381. device = parameters.device;
  47382. }
  47383. device.lost.then( ( info ) => {
  47384. const deviceLossInfo = {
  47385. api: 'WebGPU',
  47386. message: info.message || 'Unknown reason',
  47387. reason: info.reason || null,
  47388. originalEvent: info
  47389. };
  47390. renderer.onDeviceLost( deviceLossInfo );
  47391. } );
  47392. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  47393. this.device = device;
  47394. this.context = context;
  47395. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  47396. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  47397. this.context.configure( {
  47398. device: this.device,
  47399. format: this.utils.getPreferredCanvasFormat(),
  47400. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  47401. alphaMode: alphaMode
  47402. } );
  47403. this.updateSize();
  47404. }
  47405. /**
  47406. * The coordinate system of the backend.
  47407. *
  47408. * @type {Number}
  47409. * @readonly
  47410. */
  47411. get coordinateSystem() {
  47412. return WebGPUCoordinateSystem;
  47413. }
  47414. /**
  47415. * This method performs a readback operation by moving buffer data from
  47416. * a storage buffer attribute from the GPU to the CPU.
  47417. *
  47418. * @async
  47419. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47420. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47421. */
  47422. async getArrayBufferAsync( attribute ) {
  47423. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47424. }
  47425. /**
  47426. * Returns the backend's rendering context.
  47427. *
  47428. * @return {GPUCanvasContext} The rendering context.
  47429. */
  47430. getContext() {
  47431. return this.context;
  47432. }
  47433. /**
  47434. * Returns the default render pass descriptor.
  47435. *
  47436. * In WebGPU, the default framebuffer must be configured
  47437. * like custom framebuffers so the backend needs a render
  47438. * pass descriptor even when rendering directly to screen.
  47439. *
  47440. * @private
  47441. * @return {Object} The render pass descriptor.
  47442. */
  47443. _getDefaultRenderPassDescriptor() {
  47444. let descriptor = this.defaultRenderPassdescriptor;
  47445. if ( descriptor === null ) {
  47446. const renderer = this.renderer;
  47447. descriptor = {
  47448. colorAttachments: [ {
  47449. view: null
  47450. } ],
  47451. };
  47452. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  47453. descriptor.depthStencilAttachment = {
  47454. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  47455. };
  47456. }
  47457. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47458. if ( this.renderer.samples > 0 ) {
  47459. colorAttachment.view = this.colorBuffer.createView();
  47460. } else {
  47461. colorAttachment.resolveTarget = undefined;
  47462. }
  47463. this.defaultRenderPassdescriptor = descriptor;
  47464. }
  47465. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47466. if ( this.renderer.samples > 0 ) {
  47467. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  47468. } else {
  47469. colorAttachment.view = this.context.getCurrentTexture().createView();
  47470. }
  47471. return descriptor;
  47472. }
  47473. /**
  47474. * Returns the render pass descriptor for the given render context.
  47475. *
  47476. * @private
  47477. * @param {RenderContext} renderContext - The render context.
  47478. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  47479. * @return {Object} The render pass descriptor.
  47480. */
  47481. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  47482. const renderTarget = renderContext.renderTarget;
  47483. const renderTargetData = this.get( renderTarget );
  47484. let descriptors = renderTargetData.descriptors;
  47485. if ( descriptors === undefined ||
  47486. renderTargetData.width !== renderTarget.width ||
  47487. renderTargetData.height !== renderTarget.height ||
  47488. renderTargetData.dimensions !== renderTarget.dimensions ||
  47489. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  47490. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  47491. renderTargetData.samples !== renderTarget.samples ||
  47492. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  47493. ) {
  47494. descriptors = {};
  47495. renderTargetData.descriptors = descriptors;
  47496. // dispose
  47497. const onDispose = () => {
  47498. renderTarget.removeEventListener( 'dispose', onDispose );
  47499. this.delete( renderTarget );
  47500. };
  47501. renderTarget.addEventListener( 'dispose', onDispose );
  47502. }
  47503. const cacheKey = renderContext.getCacheKey();
  47504. let descriptor = descriptors[ cacheKey ];
  47505. if ( descriptor === undefined ) {
  47506. const textures = renderContext.textures;
  47507. const colorAttachments = [];
  47508. let sliceIndex;
  47509. for ( let i = 0; i < textures.length; i ++ ) {
  47510. const textureData = this.get( textures[ i ] );
  47511. const viewDescriptor = {
  47512. label: `colorAttachment_${ i }`,
  47513. baseMipLevel: renderContext.activeMipmapLevel,
  47514. mipLevelCount: 1,
  47515. baseArrayLayer: renderContext.activeCubeFace,
  47516. arrayLayerCount: 1,
  47517. dimension: GPUTextureViewDimension.TwoD
  47518. };
  47519. if ( renderTarget.isRenderTarget3D ) {
  47520. sliceIndex = renderContext.activeCubeFace;
  47521. viewDescriptor.baseArrayLayer = 0;
  47522. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  47523. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47524. } else if ( renderTarget.isRenderTargetArray ) {
  47525. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  47526. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  47527. }
  47528. const textureView = textureData.texture.createView( viewDescriptor );
  47529. let view, resolveTarget;
  47530. if ( textureData.msaaTexture !== undefined ) {
  47531. view = textureData.msaaTexture.createView();
  47532. resolveTarget = textureView;
  47533. } else {
  47534. view = textureView;
  47535. resolveTarget = undefined;
  47536. }
  47537. colorAttachments.push( {
  47538. view,
  47539. depthSlice: sliceIndex,
  47540. resolveTarget,
  47541. loadOp: GPULoadOp.Load,
  47542. storeOp: GPUStoreOp.Store,
  47543. ...colorAttachmentsConfig
  47544. } );
  47545. }
  47546. descriptor = {
  47547. colorAttachments,
  47548. };
  47549. if ( renderContext.depth ) {
  47550. const depthTextureData = this.get( renderContext.depthTexture );
  47551. const depthStencilAttachment = {
  47552. view: depthTextureData.texture.createView()
  47553. };
  47554. descriptor.depthStencilAttachment = depthStencilAttachment;
  47555. }
  47556. descriptors[ cacheKey ] = descriptor;
  47557. renderTargetData.width = renderTarget.width;
  47558. renderTargetData.height = renderTarget.height;
  47559. renderTargetData.samples = renderTarget.samples;
  47560. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  47561. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  47562. renderTargetData.dimensions = renderTarget.dimensions;
  47563. renderTargetData.depthSlice = sliceIndex;
  47564. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  47565. }
  47566. return descriptor;
  47567. }
  47568. /**
  47569. * This method is executed at the beginning of a render call and prepares
  47570. * the WebGPU state for upcoming render calls
  47571. *
  47572. * @param {RenderContext} renderContext - The render context.
  47573. */
  47574. beginRender( renderContext ) {
  47575. const renderContextData = this.get( renderContext );
  47576. const device = this.device;
  47577. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47578. let occlusionQuerySet;
  47579. if ( occlusionQueryCount > 0 ) {
  47580. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  47581. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  47582. // Get a reference to the array of objects with queries. The renderContextData property
  47583. // can be changed by another render pass before the buffer.mapAsyc() completes.
  47584. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  47585. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  47586. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  47587. //
  47588. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  47589. renderContextData.occlusionQuerySet = occlusionQuerySet;
  47590. renderContextData.occlusionQueryIndex = 0;
  47591. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  47592. renderContextData.lastOcclusionObject = null;
  47593. }
  47594. let descriptor;
  47595. if ( renderContext.textures === null ) {
  47596. descriptor = this._getDefaultRenderPassDescriptor();
  47597. } else {
  47598. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  47599. }
  47600. this.initTimestampQuery( renderContext, descriptor );
  47601. descriptor.occlusionQuerySet = occlusionQuerySet;
  47602. const depthStencilAttachment = descriptor.depthStencilAttachment;
  47603. if ( renderContext.textures !== null ) {
  47604. const colorAttachments = descriptor.colorAttachments;
  47605. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  47606. const colorAttachment = colorAttachments[ i ];
  47607. if ( renderContext.clearColor ) {
  47608. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  47609. colorAttachment.loadOp = GPULoadOp.Clear;
  47610. colorAttachment.storeOp = GPUStoreOp.Store;
  47611. } else {
  47612. colorAttachment.loadOp = GPULoadOp.Load;
  47613. colorAttachment.storeOp = GPUStoreOp.Store;
  47614. }
  47615. }
  47616. } else {
  47617. const colorAttachment = descriptor.colorAttachments[ 0 ];
  47618. if ( renderContext.clearColor ) {
  47619. colorAttachment.clearValue = renderContext.clearColorValue;
  47620. colorAttachment.loadOp = GPULoadOp.Clear;
  47621. colorAttachment.storeOp = GPUStoreOp.Store;
  47622. } else {
  47623. colorAttachment.loadOp = GPULoadOp.Load;
  47624. colorAttachment.storeOp = GPUStoreOp.Store;
  47625. }
  47626. }
  47627. //
  47628. if ( renderContext.depth ) {
  47629. if ( renderContext.clearDepth ) {
  47630. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  47631. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  47632. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47633. } else {
  47634. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  47635. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47636. }
  47637. }
  47638. if ( renderContext.stencil ) {
  47639. if ( renderContext.clearStencil ) {
  47640. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  47641. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  47642. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47643. } else {
  47644. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  47645. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47646. }
  47647. }
  47648. //
  47649. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  47650. const currentPass = encoder.beginRenderPass( descriptor );
  47651. //
  47652. renderContextData.descriptor = descriptor;
  47653. renderContextData.encoder = encoder;
  47654. renderContextData.currentPass = currentPass;
  47655. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47656. renderContextData.renderBundles = [];
  47657. //
  47658. if ( renderContext.viewport ) {
  47659. this.updateViewport( renderContext );
  47660. }
  47661. if ( renderContext.scissor ) {
  47662. const { x, y, width, height } = renderContext.scissorValue;
  47663. currentPass.setScissorRect( x, y, width, height );
  47664. }
  47665. }
  47666. /**
  47667. * This method is executed at the end of a render call and finalizes work
  47668. * after draw calls.
  47669. *
  47670. * @param {RenderContext} renderContext - The render context.
  47671. */
  47672. finishRender( renderContext ) {
  47673. const renderContextData = this.get( renderContext );
  47674. const occlusionQueryCount = renderContext.occlusionQueryCount;
  47675. if ( renderContextData.renderBundles.length > 0 ) {
  47676. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  47677. }
  47678. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  47679. renderContextData.currentPass.endOcclusionQuery();
  47680. }
  47681. renderContextData.currentPass.end();
  47682. if ( occlusionQueryCount > 0 ) {
  47683. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  47684. //
  47685. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  47686. if ( queryResolveBuffer === undefined ) {
  47687. queryResolveBuffer = this.device.createBuffer(
  47688. {
  47689. size: bufferSize,
  47690. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  47691. }
  47692. );
  47693. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  47694. }
  47695. //
  47696. const readBuffer = this.device.createBuffer(
  47697. {
  47698. size: bufferSize,
  47699. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47700. }
  47701. );
  47702. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  47703. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  47704. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  47705. renderContextData.occlusionQueryBuffer = readBuffer;
  47706. //
  47707. this.resolveOccludedAsync( renderContext );
  47708. }
  47709. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  47710. //
  47711. if ( renderContext.textures !== null ) {
  47712. const textures = renderContext.textures;
  47713. for ( let i = 0; i < textures.length; i ++ ) {
  47714. const texture = textures[ i ];
  47715. if ( texture.generateMipmaps === true ) {
  47716. this.textureUtils.generateMipmaps( texture );
  47717. }
  47718. }
  47719. }
  47720. }
  47721. /**
  47722. * Returns `true` if the given 3D object is fully occluded by other
  47723. * 3D objects in the scene.
  47724. *
  47725. * @param {RenderContext} renderContext - The render context.
  47726. * @param {Object3D} object - The 3D object to test.
  47727. * @return {Boolean} Whether the 3D object is fully occluded or not.
  47728. */
  47729. isOccluded( renderContext, object ) {
  47730. const renderContextData = this.get( renderContext );
  47731. return renderContextData.occluded && renderContextData.occluded.has( object );
  47732. }
  47733. /**
  47734. * This method processes the result of occlusion queries and writes it
  47735. * into render context data.
  47736. *
  47737. * @async
  47738. * @param {RenderContext} renderContext - The render context.
  47739. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  47740. */
  47741. async resolveOccludedAsync( renderContext ) {
  47742. const renderContextData = this.get( renderContext );
  47743. // handle occlusion query results
  47744. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  47745. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  47746. const occluded = new WeakSet();
  47747. renderContextData.currentOcclusionQueryObjects = null;
  47748. renderContextData.currentOcclusionQueryBuffer = null;
  47749. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  47750. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  47751. const results = new BigUint64Array( buffer );
  47752. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  47753. if ( results[ i ] === BigInt( 0 ) ) {
  47754. occluded.add( currentOcclusionQueryObjects[ i ] );
  47755. }
  47756. }
  47757. currentOcclusionQueryBuffer.destroy();
  47758. renderContextData.occluded = occluded;
  47759. }
  47760. }
  47761. /**
  47762. * Updates the viewport with the values from the given render context.
  47763. *
  47764. * @param {RenderContext} renderContext - The render context.
  47765. */
  47766. updateViewport( renderContext ) {
  47767. const { currentPass } = this.get( renderContext );
  47768. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  47769. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  47770. }
  47771. /**
  47772. * Performs a clear operation.
  47773. *
  47774. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  47775. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  47776. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  47777. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  47778. */
  47779. clear( color, depth, stencil, renderTargetContext = null ) {
  47780. const device = this.device;
  47781. const renderer = this.renderer;
  47782. let colorAttachments = [];
  47783. let depthStencilAttachment;
  47784. let clearValue;
  47785. let supportsDepth;
  47786. let supportsStencil;
  47787. if ( color ) {
  47788. const clearColor = this.getClearColor();
  47789. if ( this.renderer.alpha === true ) {
  47790. // premultiply alpha
  47791. const a = clearColor.a;
  47792. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  47793. } else {
  47794. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  47795. }
  47796. }
  47797. if ( renderTargetContext === null ) {
  47798. supportsDepth = renderer.depth;
  47799. supportsStencil = renderer.stencil;
  47800. const descriptor = this._getDefaultRenderPassDescriptor();
  47801. if ( color ) {
  47802. colorAttachments = descriptor.colorAttachments;
  47803. const colorAttachment = colorAttachments[ 0 ];
  47804. colorAttachment.clearValue = clearValue;
  47805. colorAttachment.loadOp = GPULoadOp.Clear;
  47806. colorAttachment.storeOp = GPUStoreOp.Store;
  47807. }
  47808. if ( supportsDepth || supportsStencil ) {
  47809. depthStencilAttachment = descriptor.depthStencilAttachment;
  47810. }
  47811. } else {
  47812. supportsDepth = renderTargetContext.depth;
  47813. supportsStencil = renderTargetContext.stencil;
  47814. if ( color ) {
  47815. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear, clearValue } );
  47816. colorAttachments = descriptor.colorAttachments;
  47817. }
  47818. if ( supportsDepth || supportsStencil ) {
  47819. const depthTextureData = this.get( renderTargetContext.depthTexture );
  47820. depthStencilAttachment = {
  47821. view: depthTextureData.texture.createView()
  47822. };
  47823. }
  47824. }
  47825. //
  47826. if ( supportsDepth ) {
  47827. if ( depth ) {
  47828. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  47829. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  47830. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47831. } else {
  47832. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  47833. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  47834. }
  47835. }
  47836. //
  47837. if ( supportsStencil ) {
  47838. if ( stencil ) {
  47839. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  47840. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  47841. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47842. } else {
  47843. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  47844. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  47845. }
  47846. }
  47847. //
  47848. const encoder = device.createCommandEncoder( { label: 'clear' } );
  47849. const currentPass = encoder.beginRenderPass( {
  47850. colorAttachments,
  47851. depthStencilAttachment
  47852. } );
  47853. currentPass.end();
  47854. device.queue.submit( [ encoder.finish() ] );
  47855. }
  47856. // compute
  47857. /**
  47858. * This method is executed at the beginning of a compute call and
  47859. * prepares the state for upcoming compute tasks.
  47860. *
  47861. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47862. */
  47863. beginCompute( computeGroup ) {
  47864. const groupGPU = this.get( computeGroup );
  47865. const descriptor = {
  47866. label: 'computeGroup_' + computeGroup.id
  47867. };
  47868. this.initTimestampQuery( computeGroup, descriptor );
  47869. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  47870. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  47871. }
  47872. /**
  47873. * Executes a compute command for the given compute node.
  47874. *
  47875. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  47876. * @param {Node} computeNode - The compute node.
  47877. * @param {Array<BindGroup>} bindings - The bindings.
  47878. * @param {ComputePipeline} pipeline - The compute pipeline.
  47879. */
  47880. compute( computeGroup, computeNode, bindings, pipeline ) {
  47881. const { passEncoderGPU } = this.get( computeGroup );
  47882. // pipeline
  47883. const pipelineGPU = this.get( pipeline ).pipeline;
  47884. passEncoderGPU.setPipeline( pipelineGPU );
  47885. // bind groups
  47886. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  47887. const bindGroup = bindings[ i ];
  47888. const bindingsData = this.get( bindGroup );
  47889. passEncoderGPU.setBindGroup( i, bindingsData.group );
  47890. }
  47891. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  47892. const computeNodeData = this.get( computeNode );
  47893. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  47894. const { dispatchSize } = computeNodeData;
  47895. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  47896. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  47897. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  47898. } else {
  47899. dispatchSize.x = computeNode.dispatchCount;
  47900. }
  47901. passEncoderGPU.dispatchWorkgroups(
  47902. dispatchSize.x,
  47903. dispatchSize.y,
  47904. dispatchSize.z
  47905. );
  47906. }
  47907. /**
  47908. * This method is executed at the end of a compute call and
  47909. * finalizes work after compute tasks.
  47910. *
  47911. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  47912. */
  47913. finishCompute( computeGroup ) {
  47914. const groupData = this.get( computeGroup );
  47915. groupData.passEncoderGPU.end();
  47916. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  47917. }
  47918. /**
  47919. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  47920. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  47921. *
  47922. * @async
  47923. * @return {Promise} A Promise that resolves when synchronization has been finished.
  47924. */
  47925. async waitForGPU() {
  47926. await this.device.queue.onSubmittedWorkDone();
  47927. }
  47928. // render object
  47929. /**
  47930. * Executes a draw command for the given render object.
  47931. *
  47932. * @param {RenderObject} renderObject - The render object to draw.
  47933. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  47934. */
  47935. draw( renderObject, info ) {
  47936. const { object, context, pipeline } = renderObject;
  47937. const bindings = renderObject.getBindings();
  47938. const renderContextData = this.get( context );
  47939. const pipelineGPU = this.get( pipeline ).pipeline;
  47940. const currentSets = renderContextData.currentSets;
  47941. const passEncoderGPU = renderContextData.currentPass;
  47942. const drawParams = renderObject.getDrawParameters();
  47943. if ( drawParams === null ) return;
  47944. // pipeline
  47945. if ( currentSets.pipeline !== pipelineGPU ) {
  47946. passEncoderGPU.setPipeline( pipelineGPU );
  47947. currentSets.pipeline = pipelineGPU;
  47948. }
  47949. // bind groups
  47950. const currentBindingGroups = currentSets.bindingGroups;
  47951. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  47952. const bindGroup = bindings[ i ];
  47953. const bindingsData = this.get( bindGroup );
  47954. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  47955. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  47956. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  47957. }
  47958. }
  47959. // attributes
  47960. const index = renderObject.getIndex();
  47961. const hasIndex = ( index !== null );
  47962. // index
  47963. if ( hasIndex === true ) {
  47964. if ( currentSets.index !== index ) {
  47965. const buffer = this.get( index ).buffer;
  47966. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  47967. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  47968. currentSets.index = index;
  47969. }
  47970. }
  47971. // vertex buffers
  47972. const vertexBuffers = renderObject.getVertexBuffers();
  47973. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  47974. const vertexBuffer = vertexBuffers[ i ];
  47975. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  47976. const buffer = this.get( vertexBuffer ).buffer;
  47977. passEncoderGPU.setVertexBuffer( i, buffer );
  47978. currentSets.attributes[ i ] = vertexBuffer;
  47979. }
  47980. }
  47981. // occlusion queries - handle multiple consecutive draw calls for an object
  47982. if ( renderContextData.occlusionQuerySet !== undefined ) {
  47983. const lastObject = renderContextData.lastOcclusionObject;
  47984. if ( lastObject !== object ) {
  47985. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  47986. passEncoderGPU.endOcclusionQuery();
  47987. renderContextData.occlusionQueryIndex ++;
  47988. }
  47989. if ( object.occlusionTest === true ) {
  47990. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  47991. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  47992. }
  47993. renderContextData.lastOcclusionObject = object;
  47994. }
  47995. }
  47996. // draw
  47997. const draw = () => {
  47998. if ( object.isBatchedMesh === true ) {
  47999. const starts = object._multiDrawStarts;
  48000. const counts = object._multiDrawCounts;
  48001. const drawCount = object._multiDrawCount;
  48002. const drawInstances = object._multiDrawInstances;
  48003. for ( let i = 0; i < drawCount; i ++ ) {
  48004. const count = drawInstances ? drawInstances[ i ] : 1;
  48005. const firstInstance = count > 1 ? 0 : i;
  48006. if ( hasIndex === true ) {
  48007. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  48008. } else {
  48009. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  48010. }
  48011. }
  48012. } else if ( hasIndex === true ) {
  48013. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  48014. const indirect = renderObject.getIndirect();
  48015. if ( indirect !== null ) {
  48016. const buffer = this.get( indirect ).buffer;
  48017. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  48018. } else {
  48019. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  48020. }
  48021. info.update( object, indexCount, instanceCount );
  48022. } else {
  48023. const { vertexCount, instanceCount, firstVertex } = drawParams;
  48024. const indirect = renderObject.getIndirect();
  48025. if ( indirect !== null ) {
  48026. const buffer = this.get( indirect ).buffer;
  48027. passEncoderGPU.drawIndirect( buffer, 0 );
  48028. } else {
  48029. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  48030. }
  48031. info.update( object, vertexCount, instanceCount );
  48032. }
  48033. };
  48034. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  48035. const cameraData = this.get( renderObject.camera );
  48036. const cameras = renderObject.camera.cameras;
  48037. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  48038. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  48039. const bindingsData = this.get( cameraIndex );
  48040. const indexesGPU = [];
  48041. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  48042. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48043. data[ 0 ] = i;
  48044. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  48045. indexesGPU.push( bindGroupIndex );
  48046. }
  48047. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  48048. }
  48049. const pixelRatio = this.renderer.getPixelRatio();
  48050. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  48051. const subCamera = cameras[ i ];
  48052. if ( object.layers.test( subCamera.layers ) ) {
  48053. const vp = subCamera.viewport;
  48054. passEncoderGPU.setViewport(
  48055. Math.floor( vp.x * pixelRatio ),
  48056. Math.floor( vp.y * pixelRatio ),
  48057. Math.floor( vp.width * pixelRatio ),
  48058. Math.floor( vp.height * pixelRatio ),
  48059. context.viewportValue.minDepth,
  48060. context.viewportValue.maxDepth
  48061. );
  48062. passEncoderGPU.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  48063. draw();
  48064. }
  48065. }
  48066. } else {
  48067. draw();
  48068. }
  48069. }
  48070. // cache key
  48071. /**
  48072. * Returns `true` if the render pipeline requires an update.
  48073. *
  48074. * @param {RenderObject} renderObject - The render object.
  48075. * @return {Boolean} Whether the render pipeline requires an update or not.
  48076. */
  48077. needsRenderUpdate( renderObject ) {
  48078. const data = this.get( renderObject );
  48079. const { object, material } = renderObject;
  48080. const utils = this.utils;
  48081. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  48082. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  48083. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  48084. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  48085. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  48086. let needsUpdate = false;
  48087. if ( data.material !== material || data.materialVersion !== material.version ||
  48088. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  48089. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  48090. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  48091. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  48092. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  48093. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  48094. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  48095. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  48096. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  48097. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  48098. data.primitiveTopology !== primitiveTopology ||
  48099. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  48100. ) {
  48101. data.material = material; data.materialVersion = material.version;
  48102. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  48103. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  48104. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  48105. data.colorWrite = material.colorWrite;
  48106. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  48107. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  48108. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  48109. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  48110. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  48111. data.sampleCount = sampleCount;
  48112. data.colorSpace = colorSpace;
  48113. data.colorFormat = colorFormat;
  48114. data.depthStencilFormat = depthStencilFormat;
  48115. data.primitiveTopology = primitiveTopology;
  48116. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  48117. needsUpdate = true;
  48118. }
  48119. return needsUpdate;
  48120. }
  48121. /**
  48122. * Returns a cache key that is used to identify render pipelines.
  48123. *
  48124. * @param {RenderObject} renderObject - The render object.
  48125. * @return {String} The cache key.
  48126. */
  48127. getRenderCacheKey( renderObject ) {
  48128. const { object, material } = renderObject;
  48129. const utils = this.utils;
  48130. const renderContext = renderObject.context;
  48131. return [
  48132. material.transparent, material.blending, material.premultipliedAlpha,
  48133. material.blendSrc, material.blendDst, material.blendEquation,
  48134. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  48135. material.colorWrite,
  48136. material.depthWrite, material.depthTest, material.depthFunc,
  48137. material.stencilWrite, material.stencilFunc,
  48138. material.stencilFail, material.stencilZFail, material.stencilZPass,
  48139. material.stencilFuncMask, material.stencilWriteMask,
  48140. material.side,
  48141. utils.getSampleCountRenderContext( renderContext ),
  48142. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  48143. utils.getPrimitiveTopology( object, material ),
  48144. renderObject.getGeometryCacheKey(),
  48145. renderObject.clippingContextCacheKey
  48146. ].join();
  48147. }
  48148. // textures
  48149. /**
  48150. * Creates a GPU sampler for the given texture.
  48151. *
  48152. * @param {Texture} texture - The texture to create the sampler for.
  48153. */
  48154. createSampler( texture ) {
  48155. this.textureUtils.createSampler( texture );
  48156. }
  48157. /**
  48158. * Destroys the GPU sampler for the given texture.
  48159. *
  48160. * @param {Texture} texture - The texture to destroy the sampler for.
  48161. */
  48162. destroySampler( texture ) {
  48163. this.textureUtils.destroySampler( texture );
  48164. }
  48165. /**
  48166. * Creates a default texture for the given texture that can be used
  48167. * as a placeholder until the actual texture is ready for usage.
  48168. *
  48169. * @param {Texture} texture - The texture to create a default texture for.
  48170. */
  48171. createDefaultTexture( texture ) {
  48172. this.textureUtils.createDefaultTexture( texture );
  48173. }
  48174. /**
  48175. * Defines a texture on the GPU for the given texture object.
  48176. *
  48177. * @param {Texture} texture - The texture.
  48178. * @param {Object} [options={}] - Optional configuration parameter.
  48179. */
  48180. createTexture( texture, options ) {
  48181. this.textureUtils.createTexture( texture, options );
  48182. }
  48183. /**
  48184. * Uploads the updated texture data to the GPU.
  48185. *
  48186. * @param {Texture} texture - The texture.
  48187. * @param {Object} [options={}] - Optional configuration parameter.
  48188. */
  48189. updateTexture( texture, options ) {
  48190. this.textureUtils.updateTexture( texture, options );
  48191. }
  48192. /**
  48193. * Generates mipmaps for the given texture.
  48194. *
  48195. * @param {Texture} texture - The texture.
  48196. */
  48197. generateMipmaps( texture ) {
  48198. this.textureUtils.generateMipmaps( texture );
  48199. }
  48200. /**
  48201. * Destroys the GPU data for the given texture object.
  48202. *
  48203. * @param {Texture} texture - The texture.
  48204. */
  48205. destroyTexture( texture ) {
  48206. this.textureUtils.destroyTexture( texture );
  48207. }
  48208. /**
  48209. * Returns texture data as a typed array.
  48210. *
  48211. * @async
  48212. * @param {Texture} texture - The texture to copy.
  48213. * @param {Number} x - The x coordinate of the copy origin.
  48214. * @param {Number} y - The y coordinate of the copy origin.
  48215. * @param {Number} width - The width of the copy.
  48216. * @param {Number} height - The height of the copy.
  48217. * @param {Number} faceIndex - The face index.
  48218. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  48219. */
  48220. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  48221. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  48222. }
  48223. /**
  48224. * Inits a time stamp query for the given render context.
  48225. *
  48226. * @param {RenderContext} renderContext - The render context.
  48227. * @param {Object} descriptor - The query descriptor.
  48228. */
  48229. initTimestampQuery( renderContext, descriptor ) {
  48230. if ( ! this.trackTimestamp ) return;
  48231. const type = renderContext.isComputeNode ? 'compute' : 'render';
  48232. if ( ! this.timestampQueryPool[ type ] ) {
  48233. // TODO: Variable maxQueries?
  48234. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  48235. }
  48236. const timestampQueryPool = this.timestampQueryPool[ type ];
  48237. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  48238. descriptor.timestampWrites = {
  48239. querySet: timestampQueryPool.querySet,
  48240. beginningOfPassWriteIndex: baseOffset,
  48241. endOfPassWriteIndex: baseOffset + 1,
  48242. };
  48243. }
  48244. // node builder
  48245. /**
  48246. * Returns a node builder for the given render object.
  48247. *
  48248. * @param {RenderObject} object - The render object.
  48249. * @param {Renderer} renderer - The renderer.
  48250. * @return {WGSLNodeBuilder} The node builder.
  48251. */
  48252. createNodeBuilder( object, renderer ) {
  48253. return new WGSLNodeBuilder( object, renderer );
  48254. }
  48255. // program
  48256. /**
  48257. * Creates a shader program from the given programmable stage.
  48258. *
  48259. * @param {ProgrammableStage} program - The programmable stage.
  48260. */
  48261. createProgram( program ) {
  48262. const programGPU = this.get( program );
  48263. programGPU.module = {
  48264. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  48265. entryPoint: 'main'
  48266. };
  48267. }
  48268. /**
  48269. * Destroys the shader program of the given programmable stage.
  48270. *
  48271. * @param {ProgrammableStage} program - The programmable stage.
  48272. */
  48273. destroyProgram( program ) {
  48274. this.delete( program );
  48275. }
  48276. // pipelines
  48277. /**
  48278. * Creates a render pipeline for the given render object.
  48279. *
  48280. * @param {RenderObject} renderObject - The render object.
  48281. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  48282. */
  48283. createRenderPipeline( renderObject, promises ) {
  48284. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  48285. }
  48286. /**
  48287. * Creates a compute pipeline for the given compute node.
  48288. *
  48289. * @param {ComputePipeline} computePipeline - The compute pipeline.
  48290. * @param {Array<BindGroup>} bindings - The bindings.
  48291. */
  48292. createComputePipeline( computePipeline, bindings ) {
  48293. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  48294. }
  48295. /**
  48296. * Prepares the state for encoding render bundles.
  48297. *
  48298. * @param {RenderContext} renderContext - The render context.
  48299. */
  48300. beginBundle( renderContext ) {
  48301. const renderContextData = this.get( renderContext );
  48302. renderContextData._currentPass = renderContextData.currentPass;
  48303. renderContextData._currentSets = renderContextData.currentSets;
  48304. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48305. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  48306. }
  48307. /**
  48308. * After processing render bundles this method finalizes related work.
  48309. *
  48310. * @param {RenderContext} renderContext - The render context.
  48311. * @param {RenderBundle} bundle - The render bundle.
  48312. */
  48313. finishBundle( renderContext, bundle ) {
  48314. const renderContextData = this.get( renderContext );
  48315. const bundleEncoder = renderContextData.currentPass;
  48316. const bundleGPU = bundleEncoder.finish();
  48317. this.get( bundle ).bundleGPU = bundleGPU;
  48318. // restore render pass state
  48319. renderContextData.currentSets = renderContextData._currentSets;
  48320. renderContextData.currentPass = renderContextData._currentPass;
  48321. }
  48322. /**
  48323. * Adds a render bundle to the render context data.
  48324. *
  48325. * @param {RenderContext} renderContext - The render context.
  48326. * @param {RenderBundle} bundle - The render bundle to add.
  48327. */
  48328. addBundle( renderContext, bundle ) {
  48329. const renderContextData = this.get( renderContext );
  48330. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  48331. }
  48332. // bindings
  48333. /**
  48334. * Creates bindings from the given bind group definition.
  48335. *
  48336. * @param {BindGroup} bindGroup - The bind group.
  48337. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48338. * @param {Number} cacheIndex - The cache index.
  48339. * @param {Number} version - The version.
  48340. */
  48341. createBindings( bindGroup, bindings, cacheIndex, version ) {
  48342. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  48343. }
  48344. /**
  48345. * Updates the given bind group definition.
  48346. *
  48347. * @param {BindGroup} bindGroup - The bind group.
  48348. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48349. * @param {Number} cacheIndex - The cache index.
  48350. * @param {Number} version - The version.
  48351. */
  48352. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  48353. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  48354. }
  48355. /**
  48356. * Updates a buffer binding.
  48357. *
  48358. * @param {Buffer} binding - The buffer binding to update.
  48359. */
  48360. updateBinding( binding ) {
  48361. this.bindingUtils.updateBinding( binding );
  48362. }
  48363. // attributes
  48364. /**
  48365. * Creates the buffer of an indexed shader attribute.
  48366. *
  48367. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  48368. */
  48369. createIndexAttribute( attribute ) {
  48370. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48371. }
  48372. /**
  48373. * Creates the GPU buffer of a shader attribute.
  48374. *
  48375. * @param {BufferAttribute} attribute - The buffer attribute.
  48376. */
  48377. createAttribute( attribute ) {
  48378. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48379. }
  48380. /**
  48381. * Creates the GPU buffer of a storage attribute.
  48382. *
  48383. * @param {BufferAttribute} attribute - The buffer attribute.
  48384. */
  48385. createStorageAttribute( attribute ) {
  48386. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48387. }
  48388. /**
  48389. * Creates the GPU buffer of an indirect storage attribute.
  48390. *
  48391. * @param {BufferAttribute} attribute - The buffer attribute.
  48392. */
  48393. createIndirectStorageAttribute( attribute ) {
  48394. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  48395. }
  48396. /**
  48397. * Updates the GPU buffer of a shader attribute.
  48398. *
  48399. * @param {BufferAttribute} attribute - The buffer attribute to update.
  48400. */
  48401. updateAttribute( attribute ) {
  48402. this.attributeUtils.updateAttribute( attribute );
  48403. }
  48404. /**
  48405. * Destroys the GPU buffer of a shader attribute.
  48406. *
  48407. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  48408. */
  48409. destroyAttribute( attribute ) {
  48410. this.attributeUtils.destroyAttribute( attribute );
  48411. }
  48412. // canvas
  48413. /**
  48414. * Triggers an update of the default render pass descriptor.
  48415. */
  48416. updateSize() {
  48417. this.colorBuffer = this.textureUtils.getColorBuffer();
  48418. this.defaultRenderPassdescriptor = null;
  48419. }
  48420. // utils public
  48421. /**
  48422. * Returns the maximum anisotropy texture filtering value.
  48423. *
  48424. * @return {Number} The maximum anisotropy texture filtering value.
  48425. */
  48426. getMaxAnisotropy() {
  48427. return 16;
  48428. }
  48429. /**
  48430. * Checks if the given feature is supported by the backend.
  48431. *
  48432. * @param {String} name - The feature's name.
  48433. * @return {Boolean} Whether the feature is supported or not.
  48434. */
  48435. hasFeature( name ) {
  48436. return this.device.features.has( name );
  48437. }
  48438. /**
  48439. * Copies data of the given source texture to the given destination texture.
  48440. *
  48441. * @param {Texture} srcTexture - The source texture.
  48442. * @param {Texture} dstTexture - The destination texture.
  48443. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  48444. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  48445. * @param {Number} [level=0] - The mip level to copy.
  48446. */
  48447. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  48448. let dstX = 0;
  48449. let dstY = 0;
  48450. let dstLayer = 0;
  48451. let srcX = 0;
  48452. let srcY = 0;
  48453. let srcLayer = 0;
  48454. let srcWidth = srcTexture.image.width;
  48455. let srcHeight = srcTexture.image.height;
  48456. if ( srcRegion !== null ) {
  48457. srcX = srcRegion.x;
  48458. srcY = srcRegion.y;
  48459. srcLayer = srcRegion.z || 0;
  48460. srcWidth = srcRegion.width;
  48461. srcHeight = srcRegion.height;
  48462. }
  48463. if ( dstPosition !== null ) {
  48464. dstX = dstPosition.x;
  48465. dstY = dstPosition.y;
  48466. dstLayer = dstPosition.z || 0;
  48467. }
  48468. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  48469. const sourceGPU = this.get( srcTexture ).texture;
  48470. const destinationGPU = this.get( dstTexture ).texture;
  48471. encoder.copyTextureToTexture(
  48472. {
  48473. texture: sourceGPU,
  48474. mipLevel: level,
  48475. origin: { x: srcX, y: srcY, z: srcLayer }
  48476. },
  48477. {
  48478. texture: destinationGPU,
  48479. mipLevel: level,
  48480. origin: { x: dstX, y: dstY, z: dstLayer }
  48481. },
  48482. [
  48483. srcWidth,
  48484. srcHeight,
  48485. 1
  48486. ]
  48487. );
  48488. this.device.queue.submit( [ encoder.finish() ] );
  48489. }
  48490. /**
  48491. * Copies the current bound framebuffer to the given texture.
  48492. *
  48493. * @param {Texture} texture - The destination texture.
  48494. * @param {RenderContext} renderContext - The render context.
  48495. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  48496. */
  48497. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  48498. const renderContextData = this.get( renderContext );
  48499. let sourceGPU = null;
  48500. if ( renderContext.renderTarget ) {
  48501. if ( texture.isDepthTexture ) {
  48502. sourceGPU = this.get( renderContext.depthTexture ).texture;
  48503. } else {
  48504. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  48505. }
  48506. } else {
  48507. if ( texture.isDepthTexture ) {
  48508. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  48509. } else {
  48510. sourceGPU = this.context.getCurrentTexture();
  48511. }
  48512. }
  48513. const destinationGPU = this.get( texture ).texture;
  48514. if ( sourceGPU.format !== destinationGPU.format ) {
  48515. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  48516. return;
  48517. }
  48518. let encoder;
  48519. if ( renderContextData.currentPass ) {
  48520. renderContextData.currentPass.end();
  48521. encoder = renderContextData.encoder;
  48522. } else {
  48523. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  48524. }
  48525. encoder.copyTextureToTexture(
  48526. {
  48527. texture: sourceGPU,
  48528. origin: [ rectangle.x, rectangle.y, 0 ],
  48529. },
  48530. {
  48531. texture: destinationGPU
  48532. },
  48533. [
  48534. rectangle.z,
  48535. rectangle.w
  48536. ]
  48537. );
  48538. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  48539. if ( renderContextData.currentPass ) {
  48540. const { descriptor } = renderContextData;
  48541. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  48542. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  48543. }
  48544. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48545. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48546. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  48547. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48548. if ( renderContext.viewport ) {
  48549. this.updateViewport( renderContext );
  48550. }
  48551. if ( renderContext.scissor ) {
  48552. const { x, y, width, height } = renderContext.scissorValue;
  48553. renderContextData.currentPass.setScissorRect( x, y, width, height );
  48554. }
  48555. } else {
  48556. this.device.queue.submit( [ encoder.finish() ] );
  48557. }
  48558. }
  48559. }
  48560. class IESSpotLight extends SpotLight {
  48561. constructor( color, intensity, distance, angle, penumbra, decay ) {
  48562. super( color, intensity, distance, angle, penumbra, decay );
  48563. this.iesMap = null;
  48564. }
  48565. copy( source, recursive ) {
  48566. super.copy( source, recursive );
  48567. this.iesMap = source.iesMap;
  48568. return this;
  48569. }
  48570. }
  48571. /**
  48572. * This version of a node library represents a basic version
  48573. * just focusing on lights and tone mapping techniques.
  48574. *
  48575. * @private
  48576. * @augments NodeLibrary
  48577. */
  48578. class BasicNodeLibrary extends NodeLibrary {
  48579. /**
  48580. * Constructs a new basic node library.
  48581. */
  48582. constructor() {
  48583. super();
  48584. this.addLight( PointLightNode, PointLight );
  48585. this.addLight( DirectionalLightNode, DirectionalLight );
  48586. this.addLight( RectAreaLightNode, RectAreaLight );
  48587. this.addLight( SpotLightNode, SpotLight );
  48588. this.addLight( AmbientLightNode, AmbientLight );
  48589. this.addLight( HemisphereLightNode, HemisphereLight );
  48590. this.addLight( LightProbeNode, LightProbe );
  48591. this.addLight( IESSpotLightNode, IESSpotLight );
  48592. this.addToneMapping( linearToneMapping, LinearToneMapping );
  48593. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  48594. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  48595. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  48596. this.addToneMapping( agxToneMapping, AgXToneMapping );
  48597. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  48598. }
  48599. }
  48600. /**
  48601. * This alternative version of {@link WebGPURenderer} only supports node materials.
  48602. * So classes like `MeshBasicMaterial` are not compatible.
  48603. *
  48604. * @private
  48605. * @augments module:Renderer~Renderer
  48606. */
  48607. class WebGPURenderer extends Renderer {
  48608. /**
  48609. * Constructs a new WebGPU renderer.
  48610. *
  48611. * @param {Object} parameters - The configuration parameter.
  48612. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48613. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48614. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48615. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48616. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48617. * @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.
  48618. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it WebGL 2 backend no matter if WebGPU is supported or not.
  48619. * @param {Number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  48620. * @param {Number} [parameters.colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  48621. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  48622. */
  48623. constructor( parameters = {} ) {
  48624. let BackendClass;
  48625. if ( parameters.forceWebGL ) {
  48626. BackendClass = WebGLBackend;
  48627. } else {
  48628. BackendClass = WebGPUBackend;
  48629. parameters.getFallback = () => {
  48630. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  48631. return new WebGLBackend( parameters );
  48632. };
  48633. }
  48634. const backend = new BackendClass( parameters );
  48635. super( backend, parameters );
  48636. /**
  48637. * The generic default value is overwritten with the
  48638. * standard node library for type mapping. Material
  48639. * mapping is not supported with this version.
  48640. *
  48641. * @type {BasicNodeLibrary}
  48642. */
  48643. this.library = new BasicNodeLibrary();
  48644. /**
  48645. * This flag can be used for type testing.
  48646. *
  48647. * @type {Boolean}
  48648. * @readonly
  48649. * @default true
  48650. */
  48651. this.isWebGPURenderer = true;
  48652. }
  48653. }
  48654. /**
  48655. * A specialized group which enables applications access to the
  48656. * Render Bundle API of WebGPU. The group with all its descendant nodes
  48657. * are considered as one render bundle and processed as such by
  48658. * the renderer.
  48659. *
  48660. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  48661. * With a WebGL backend, the group can technically be rendered but without
  48662. * any performance improvements.
  48663. *
  48664. * @augments Group
  48665. */
  48666. class BundleGroup extends Group {
  48667. /**
  48668. * Constructs a new bundle group.
  48669. */
  48670. constructor() {
  48671. super();
  48672. /**
  48673. * This flag can be used for type testing.
  48674. *
  48675. * @type {Boolean}
  48676. * @readonly
  48677. * @default true
  48678. */
  48679. this.isBundleGroup = true;
  48680. /**
  48681. * This property is only relevant for detecting types
  48682. * during serialization/deserialization. It should always
  48683. * match the class name.
  48684. *
  48685. * @type {String}
  48686. * @readonly
  48687. * @default 'BundleGroup'
  48688. */
  48689. this.type = 'BundleGroup';
  48690. /**
  48691. * Whether the bundle is static or not. When set to `true`, the structure
  48692. * is assumed to be static and does not change. E.g. no new objects are
  48693. * added to the group
  48694. *
  48695. * If a change is required, an update can still be forced by setting the
  48696. * `needsUpdate` flag to `true`.
  48697. *
  48698. * @type {Boolean}
  48699. * @default true
  48700. */
  48701. this.static = true;
  48702. /**
  48703. * The bundle group's version.
  48704. *
  48705. * @type {Number}
  48706. * @readonly
  48707. * @default 0
  48708. */
  48709. this.version = 0;
  48710. }
  48711. /**
  48712. * Set this property to `true` when the bundle group has changed.
  48713. *
  48714. * @type {Boolean}
  48715. * @default false
  48716. * @param {Boolean} value
  48717. */
  48718. set needsUpdate( value ) {
  48719. if ( value === true ) this.version ++;
  48720. }
  48721. }
  48722. /**
  48723. * This module is responsible to manage the post processing setups in apps.
  48724. * You usually create a single instance of this class and use it to define
  48725. * the output of your post processing effect chain.
  48726. * ```js
  48727. * const postProcessing = new PostProcessing( renderer );
  48728. *
  48729. * const scenePass = pass( scene, camera );
  48730. *
  48731. * postProcessing.outputNode = scenePass;
  48732. * ```
  48733. */
  48734. class PostProcessing {
  48735. /**
  48736. * Constructs a new post processing management module.
  48737. *
  48738. * @param {Renderer} renderer - A reference to the renderer.
  48739. * @param {Node<vec4>} outputNode - An optional output node.
  48740. */
  48741. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  48742. /**
  48743. * A reference to the renderer.
  48744. *
  48745. * @type {Renderer}
  48746. */
  48747. this.renderer = renderer;
  48748. /**
  48749. * A node which defines the final output of the post
  48750. * processing. This is usually the last node in a chain
  48751. * of effect nodes.
  48752. *
  48753. * @type {Node<vec4>}
  48754. */
  48755. this.outputNode = outputNode;
  48756. /**
  48757. * Whether the default output tone mapping and color
  48758. * space transformation should be enabled or not.
  48759. *
  48760. * It is enabled by default by it must be disabled when
  48761. * effects must be executed after tone mapping and color
  48762. * space conversion. A typical example is FXAA which
  48763. * requires sRGB input.
  48764. *
  48765. * When set to `false`, the app must control the output
  48766. * transformation with `RenderOutputNode`.
  48767. *
  48768. * ```js
  48769. * const outputPass = renderOutput( scenePass );
  48770. * ```
  48771. *
  48772. * @type {Boolean}
  48773. */
  48774. this.outputColorTransform = true;
  48775. /**
  48776. * Must be set to `true` when the output node changes.
  48777. *
  48778. * @type {Node<vec4>}
  48779. */
  48780. this.needsUpdate = true;
  48781. const material = new NodeMaterial();
  48782. material.name = 'PostProcessing';
  48783. /**
  48784. * The full screen quad that is used to render
  48785. * the effects.
  48786. *
  48787. * @private
  48788. * @type {QuadMesh}
  48789. */
  48790. this._quadMesh = new QuadMesh( material );
  48791. }
  48792. /**
  48793. * When `PostProcessing` is used to apply post processing effects,
  48794. * the application must use this version of `render()` inside
  48795. * its animation loop (not the one from the renderer).
  48796. */
  48797. render() {
  48798. this._update();
  48799. const renderer = this.renderer;
  48800. const toneMapping = renderer.toneMapping;
  48801. const outputColorSpace = renderer.outputColorSpace;
  48802. renderer.toneMapping = NoToneMapping;
  48803. renderer.outputColorSpace = LinearSRGBColorSpace;
  48804. //
  48805. this._quadMesh.render( renderer );
  48806. //
  48807. renderer.toneMapping = toneMapping;
  48808. renderer.outputColorSpace = outputColorSpace;
  48809. }
  48810. /**
  48811. * Frees internal resources.
  48812. */
  48813. dispose() {
  48814. this._quadMesh.material.dispose();
  48815. }
  48816. /**
  48817. * Updates the state of the module.
  48818. *
  48819. * @private
  48820. */
  48821. _update() {
  48822. if ( this.needsUpdate === true ) {
  48823. const renderer = this.renderer;
  48824. const toneMapping = renderer.toneMapping;
  48825. const outputColorSpace = renderer.outputColorSpace;
  48826. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  48827. this._quadMesh.material.needsUpdate = true;
  48828. this.needsUpdate = false;
  48829. }
  48830. }
  48831. /**
  48832. * When `PostProcessing` is used to apply post processing effects,
  48833. * the application must use this version of `renderAsync()` inside
  48834. * its animation loop (not the one from the renderer).
  48835. *
  48836. * @async
  48837. * @return {Promise} A Promise that resolves when the render has been finished.
  48838. */
  48839. async renderAsync() {
  48840. this._update();
  48841. const renderer = this.renderer;
  48842. const toneMapping = renderer.toneMapping;
  48843. const outputColorSpace = renderer.outputColorSpace;
  48844. renderer.toneMapping = NoToneMapping;
  48845. renderer.outputColorSpace = LinearSRGBColorSpace;
  48846. //
  48847. await this._quadMesh.renderAsync( renderer );
  48848. //
  48849. renderer.toneMapping = toneMapping;
  48850. renderer.outputColorSpace = outputColorSpace;
  48851. }
  48852. }
  48853. /**
  48854. * This special type of texture is intended for compute shaders.
  48855. * It can be used to compute the data of a texture with a compute shader.
  48856. *
  48857. * Note: This type of texture can only be used with `WebGPURenderer`
  48858. * and a WebGPU backend.
  48859. *
  48860. * @augments Texture
  48861. */
  48862. class StorageTexture extends Texture {
  48863. /**
  48864. * Constructs a new storage texture.
  48865. *
  48866. * @param {Number} [width=1] - The storage texture's width.
  48867. * @param {Number} [height=1] - The storage texture's height.
  48868. */
  48869. constructor( width = 1, height = 1 ) {
  48870. super();
  48871. /**
  48872. * The image object which just represents the texture's dimension.
  48873. *
  48874. * @type {{width: Number, height: Number}}
  48875. */
  48876. this.image = { width, height };
  48877. /**
  48878. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  48879. *
  48880. * @type {Number}
  48881. */
  48882. this.magFilter = LinearFilter;
  48883. /**
  48884. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  48885. *
  48886. * @type {Number}
  48887. */
  48888. this.minFilter = LinearFilter;
  48889. /**
  48890. * This flag can be used for type testing.
  48891. *
  48892. * @type {Boolean}
  48893. * @readonly
  48894. * @default true
  48895. */
  48896. this.isStorageTexture = true;
  48897. }
  48898. }
  48899. /**
  48900. * This special type of buffer attribute is intended for compute shaders.
  48901. * It can be used to encode draw parameters for indirect draw calls.
  48902. *
  48903. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  48904. * and a WebGPU backend.
  48905. *
  48906. * @augments StorageBufferAttribute
  48907. */
  48908. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  48909. /**
  48910. * Constructs a new storage buffer attribute.
  48911. *
  48912. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  48913. * The subsequent parameter is then obsolete.
  48914. * @param {Number} itemSize - The item size.
  48915. */
  48916. constructor( count, itemSize ) {
  48917. super( count, itemSize, Uint32Array );
  48918. /**
  48919. * This flag can be used for type testing.
  48920. *
  48921. * @type {Boolean}
  48922. * @readonly
  48923. * @default true
  48924. */
  48925. this.isIndirectStorageBufferAttribute = true;
  48926. }
  48927. }
  48928. /**
  48929. * A loader for loading node objects in the three.js JSON Object/Scene format.
  48930. *
  48931. * @augments Loader
  48932. */
  48933. class NodeLoader extends Loader {
  48934. /**
  48935. * Constructs a new node loader.
  48936. *
  48937. * @param {LoadingManager?} manager - A reference to a loading manager.
  48938. */
  48939. constructor( manager ) {
  48940. super( manager );
  48941. /**
  48942. * Represents a dictionary of textures.
  48943. *
  48944. * @type {Object<String,Texture>}
  48945. */
  48946. this.textures = {};
  48947. /**
  48948. * Represents a dictionary of node types.
  48949. *
  48950. * @type {Object<String,Node.constructor>}
  48951. */
  48952. this.nodes = {};
  48953. }
  48954. /**
  48955. * Loads the node definitions from the given URL.
  48956. *
  48957. * @param {String} url - The path/URL of the file to be loaded.
  48958. * @param {Function} onLoad - Will be called when load completes.
  48959. * @param {Function} onProgress - Will be called while load progresses.
  48960. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  48961. */
  48962. load( url, onLoad, onProgress, onError ) {
  48963. const loader = new FileLoader( this.manager );
  48964. loader.setPath( this.path );
  48965. loader.setRequestHeader( this.requestHeader );
  48966. loader.setWithCredentials( this.withCredentials );
  48967. loader.load( url, ( text ) => {
  48968. try {
  48969. onLoad( this.parse( JSON.parse( text ) ) );
  48970. } catch ( e ) {
  48971. if ( onError ) {
  48972. onError( e );
  48973. } else {
  48974. console.error( e );
  48975. }
  48976. this.manager.itemError( url );
  48977. }
  48978. }, onProgress, onError );
  48979. }
  48980. /**
  48981. * Parse the node dependencies for the loaded node.
  48982. *
  48983. * @param {Object} json - The JSON definition
  48984. * @return {Object<String,Node>} A dictionary with node dependencies.
  48985. */
  48986. parseNodes( json ) {
  48987. const nodes = {};
  48988. if ( json !== undefined ) {
  48989. for ( const nodeJSON of json ) {
  48990. const { uuid, type } = nodeJSON;
  48991. nodes[ uuid ] = this.createNodeFromType( type );
  48992. nodes[ uuid ].uuid = uuid;
  48993. }
  48994. const meta = { nodes, textures: this.textures };
  48995. for ( const nodeJSON of json ) {
  48996. nodeJSON.meta = meta;
  48997. const node = nodes[ nodeJSON.uuid ];
  48998. node.deserialize( nodeJSON );
  48999. delete nodeJSON.meta;
  49000. }
  49001. }
  49002. return nodes;
  49003. }
  49004. /**
  49005. * Parses the node from the given JSON.
  49006. *
  49007. * @param {Object} json - The JSON definition
  49008. * @return {Node} The parsed node.
  49009. */
  49010. parse( json ) {
  49011. const node = this.createNodeFromType( json.type );
  49012. node.uuid = json.uuid;
  49013. const nodes = this.parseNodes( json.nodes );
  49014. const meta = { nodes, textures: this.textures };
  49015. json.meta = meta;
  49016. node.deserialize( json );
  49017. delete json.meta;
  49018. return node;
  49019. }
  49020. /**
  49021. * Defines the dictionary of textures.
  49022. *
  49023. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  49024. * @return {NodeLoader} A reference to this loader.
  49025. */
  49026. setTextures( value ) {
  49027. this.textures = value;
  49028. return this;
  49029. }
  49030. /**
  49031. * Defines the dictionary of node types.
  49032. *
  49033. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  49034. * @return {NodeLoader} A reference to this loader.
  49035. */
  49036. setNodes( value ) {
  49037. this.nodes = value;
  49038. return this;
  49039. }
  49040. /**
  49041. * Creates a node object from the given type.
  49042. *
  49043. * @param {String} type - The node type.
  49044. * @return {Node} The created node instance.
  49045. */
  49046. createNodeFromType( type ) {
  49047. if ( this.nodes[ type ] === undefined ) {
  49048. console.error( 'THREE.NodeLoader: Node type not found:', type );
  49049. return float();
  49050. }
  49051. return nodeObject( new this.nodes[ type ]() );
  49052. }
  49053. }
  49054. /**
  49055. * A special type of material loader for loading node materials.
  49056. *
  49057. * @augments MaterialLoader
  49058. */
  49059. class NodeMaterialLoader extends MaterialLoader {
  49060. /**
  49061. * Constructs a new node material loader.
  49062. *
  49063. * @param {LoadingManager?} manager - A reference to a loading manager.
  49064. */
  49065. constructor( manager ) {
  49066. super( manager );
  49067. /**
  49068. * Represents a dictionary of node types.
  49069. *
  49070. * @type {Object<String,Node.constructor>}
  49071. */
  49072. this.nodes = {};
  49073. /**
  49074. * Represents a dictionary of node material types.
  49075. *
  49076. * @type {Object<String,NodeMaterial.constructor>}
  49077. */
  49078. this.nodeMaterials = {};
  49079. }
  49080. /**
  49081. * Parses the node material from the given JSON.
  49082. *
  49083. * @param {Object} json - The JSON definition
  49084. * @return {NodeMaterial}. The parsed material.
  49085. */
  49086. parse( json ) {
  49087. const material = super.parse( json );
  49088. const nodes = this.nodes;
  49089. const inputNodes = json.inputNodes;
  49090. for ( const property in inputNodes ) {
  49091. const uuid = inputNodes[ property ];
  49092. material[ property ] = nodes[ uuid ];
  49093. }
  49094. return material;
  49095. }
  49096. /**
  49097. * Defines the dictionary of node types.
  49098. *
  49099. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  49100. * @return {NodeLoader} A reference to this loader.
  49101. */
  49102. setNodes( value ) {
  49103. this.nodes = value;
  49104. return this;
  49105. }
  49106. /**
  49107. * Defines the dictionary of node material types.
  49108. *
  49109. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  49110. * @return {NodeLoader} A reference to this loader.
  49111. */
  49112. setNodeMaterials( value ) {
  49113. this.nodeMaterials = value;
  49114. return this;
  49115. }
  49116. /**
  49117. * Creates a node material from the given type.
  49118. *
  49119. * @param {String} type - The node material type.
  49120. * @return {Node} The created node material instance.
  49121. */
  49122. createMaterialFromType( type ) {
  49123. const materialClass = this.nodeMaterials[ type ];
  49124. if ( materialClass !== undefined ) {
  49125. return new materialClass();
  49126. }
  49127. return super.createMaterialFromType( type );
  49128. }
  49129. }
  49130. /**
  49131. * A special type of object loader for loading 3D objects using
  49132. * node materials.
  49133. *
  49134. * @augments ObjectLoader
  49135. */
  49136. class NodeObjectLoader extends ObjectLoader {
  49137. /**
  49138. * Constructs a new node object loader.
  49139. *
  49140. * @param {LoadingManager?} manager - A reference to a loading manager.
  49141. */
  49142. constructor( manager ) {
  49143. super( manager );
  49144. /**
  49145. * Represents a dictionary of node types.
  49146. *
  49147. * @type {Object<String,Node.constructor>}
  49148. */
  49149. this.nodes = {};
  49150. /**
  49151. * Represents a dictionary of node material types.
  49152. *
  49153. * @type {Object<String,NodeMaterial.constructor>}
  49154. */
  49155. this.nodeMaterials = {};
  49156. /**
  49157. * A reference to hold the `nodes` JSON property.
  49158. *
  49159. * @private
  49160. * @type {Object?}
  49161. */
  49162. this._nodesJSON = null;
  49163. }
  49164. /**
  49165. * Defines the dictionary of node types.
  49166. *
  49167. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  49168. * @return {NodeLoader} A reference to this loader.
  49169. */
  49170. setNodes( value ) {
  49171. this.nodes = value;
  49172. return this;
  49173. }
  49174. /**
  49175. * Defines the dictionary of node material types.
  49176. *
  49177. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  49178. * @return {NodeLoader} A reference to this loader.
  49179. */
  49180. setNodeMaterials( value ) {
  49181. this.nodeMaterials = value;
  49182. return this;
  49183. }
  49184. /**
  49185. * Parses the node objects from the given JSON.
  49186. *
  49187. * @param {Object} json - The JSON definition
  49188. * @param {Function} onLoad - The onLoad callback function.
  49189. * @return {Object3D}. The parsed 3D object.
  49190. */
  49191. parse( json, onLoad ) {
  49192. this._nodesJSON = json.nodes;
  49193. const data = super.parse( json, onLoad );
  49194. this._nodesJSON = null; // dispose
  49195. return data;
  49196. }
  49197. /**
  49198. * Parses the node objects from the given JSON and textures.
  49199. *
  49200. * @param {Object} json - The JSON definition
  49201. * @param {Object<String,Texture>} textures - The texture library.
  49202. * @return {Object<String,Node>}. The parsed nodes.
  49203. */
  49204. parseNodes( json, textures ) {
  49205. if ( json !== undefined ) {
  49206. const loader = new NodeLoader();
  49207. loader.setNodes( this.nodes );
  49208. loader.setTextures( textures );
  49209. return loader.parseNodes( json );
  49210. }
  49211. return {};
  49212. }
  49213. /**
  49214. * Parses the node objects from the given JSON and textures.
  49215. *
  49216. * @param {Object} json - The JSON definition
  49217. * @param {Object<String,Texture>} textures - The texture library.
  49218. * @return {Object<String,NodeMaterial>}. The parsed materials.
  49219. */
  49220. parseMaterials( json, textures ) {
  49221. const materials = {};
  49222. if ( json !== undefined ) {
  49223. const nodes = this.parseNodes( this._nodesJSON, textures );
  49224. const loader = new NodeMaterialLoader();
  49225. loader.setTextures( textures );
  49226. loader.setNodes( nodes );
  49227. loader.setNodeMaterials( this.nodeMaterials );
  49228. for ( let i = 0, l = json.length; i < l; i ++ ) {
  49229. const data = json[ i ];
  49230. materials[ data.uuid ] = loader.parse( data );
  49231. }
  49232. }
  49233. return materials;
  49234. }
  49235. }
  49236. /**
  49237. * In earlier three.js versions, clipping was defined globally
  49238. * on the renderer or on material level. This special version of
  49239. * `THREE.Group` allows to encode the clipping state into the scene
  49240. * graph. Meaning if you create an instance of this group, all
  49241. * descendant 3D objects will be affected by the respective clipping
  49242. * planes.
  49243. *
  49244. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  49245. *
  49246. * @augments Group
  49247. */
  49248. class ClippingGroup extends Group {
  49249. /**
  49250. * Constructs a new clipping group.
  49251. */
  49252. constructor() {
  49253. super();
  49254. /**
  49255. * This flag can be used for type testing.
  49256. *
  49257. * @type {Boolean}
  49258. * @readonly
  49259. * @default true
  49260. */
  49261. this.isClippingGroup = true;
  49262. /**
  49263. * An array with clipping planes.
  49264. *
  49265. * @type {Array<Plane>}
  49266. */
  49267. this.clippingPlanes = [];
  49268. /**
  49269. * Whether clipping should be enabled or not.
  49270. *
  49271. * @type {Boolean}
  49272. * @default true
  49273. */
  49274. this.enabled = true;
  49275. /**
  49276. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  49277. *
  49278. * @type {Boolean}
  49279. * @default false
  49280. */
  49281. this.clipIntersection = false;
  49282. /**
  49283. * Whether shadows should be clipped or not.
  49284. *
  49285. * @type {Boolean}
  49286. * @default false
  49287. */
  49288. this.clipShadows = false;
  49289. }
  49290. }
  49291. 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, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, 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, StructNode, StructTypeNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号