three.webgpu.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, InterleavedBufferAttribute, DynamicDrawUsage, NoColorSpace, UnsignedIntType, IntType, NearestFilter, Sphere, BackSide, Euler, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, OrthographicCamera, PerspectiveCamera, RenderTarget, CubeUVReflectionMapping, BufferGeometry, BufferAttribute, LinearSRGBColorSpace, RGBAFormat, HalfFloatType, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, Frustum, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, warnOnce, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, 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, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, 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, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RenderTargetArray, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. '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. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  347. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  348. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  349. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  350. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  351. function cyrb53( value, seed = 0 ) {
  352. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  353. if ( value instanceof Array ) {
  354. for ( let i = 0, val; i < value.length; i ++ ) {
  355. val = value[ i ];
  356. h1 = Math.imul( h1 ^ val, 2654435761 );
  357. h2 = Math.imul( h2 ^ val, 1597334677 );
  358. }
  359. } else {
  360. for ( let i = 0, ch; i < value.length; i ++ ) {
  361. ch = value.charCodeAt( i );
  362. h1 = Math.imul( h1 ^ ch, 2654435761 );
  363. h2 = Math.imul( h2 ^ ch, 1597334677 );
  364. }
  365. }
  366. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  367. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  368. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  369. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  370. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  371. }
  372. /**
  373. * Computes a hash for the given string.
  374. *
  375. * @method
  376. * @param {string} str - The string to be hashed.
  377. * @return {number} The hash.
  378. */
  379. const hashString = ( str ) => cyrb53( str );
  380. /**
  381. * Computes a hash for the given array.
  382. *
  383. * @method
  384. * @param {Array<number>} array - The array to be hashed.
  385. * @return {number} The hash.
  386. */
  387. const hashArray = ( array ) => cyrb53( array );
  388. /**
  389. * Computes a hash for the given list of parameters.
  390. *
  391. * @method
  392. * @param {...number} params - A list of parameters.
  393. * @return {number} The hash.
  394. */
  395. const hash$1 = ( ...params ) => cyrb53( params );
  396. /**
  397. * Computes a cache key for the given node.
  398. *
  399. * @method
  400. * @param {Object|Node} object - The object to be hashed.
  401. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  402. * @return {number} The hash.
  403. */
  404. function getCacheKey$1( object, force = false ) {
  405. const values = [];
  406. if ( object.isNode === true ) {
  407. values.push( object.id );
  408. object = object.getSelf();
  409. }
  410. for ( const { property, childNode } of getNodeChildren( object ) ) {
  411. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  412. }
  413. return cyrb53( values );
  414. }
  415. /**
  416. * This generator function can be used to iterate over the node children
  417. * of the given object.
  418. *
  419. * @generator
  420. * @param {Object} node - The object to be hashed.
  421. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  422. * @yields {Object} A result node holding the property, index (if available) and the child node.
  423. */
  424. function* getNodeChildren( node, toJSON = false ) {
  425. for ( const property in node ) {
  426. // Ignore private properties.
  427. if ( property.startsWith( '_' ) === true ) continue;
  428. const object = node[ property ];
  429. if ( Array.isArray( object ) === true ) {
  430. for ( let i = 0; i < object.length; i ++ ) {
  431. const child = object[ i ];
  432. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  433. yield { property, index: i, childNode: child };
  434. }
  435. }
  436. } else if ( object && object.isNode === true ) {
  437. yield { property, childNode: object };
  438. } else if ( typeof object === 'object' ) {
  439. for ( const subProperty in object ) {
  440. const child = object[ subProperty ];
  441. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  442. yield { property, index: subProperty, childNode: child };
  443. }
  444. }
  445. }
  446. }
  447. }
  448. const typeFromLength = /*@__PURE__*/ new Map( [
  449. [ 1, 'float' ],
  450. [ 2, 'vec2' ],
  451. [ 3, 'vec3' ],
  452. [ 4, 'vec4' ],
  453. [ 9, 'mat3' ],
  454. [ 16, 'mat4' ]
  455. ] );
  456. const dataFromObject = /*@__PURE__*/ new WeakMap();
  457. /**
  458. * Returns the data type for the given the length.
  459. *
  460. * @method
  461. * @param {number} length - The length.
  462. * @return {string} The data type.
  463. */
  464. function getTypeFromLength( length ) {
  465. return typeFromLength.get( length );
  466. }
  467. /**
  468. * Returns the typed array for the given data type.
  469. *
  470. * @method
  471. * @param {string} type - The data type.
  472. * @return {TypedArray} The typed array.
  473. */
  474. function getTypedArrayFromType( type ) {
  475. // Handle component type for vectors and matrices
  476. if ( /[iu]?vec\d/.test( type ) ) {
  477. // Handle int vectors
  478. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  479. // Handle uint vectors
  480. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  481. // Default to float vectors
  482. return Float32Array;
  483. }
  484. // Handle matrices (always float)
  485. if ( /mat\d/.test( type ) ) return Float32Array;
  486. // Basic types
  487. if ( /float/.test( type ) ) return Float32Array;
  488. if ( /uint/.test( type ) ) return Uint32Array;
  489. if ( /int/.test( type ) ) return Int32Array;
  490. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  491. }
  492. /**
  493. * Returns the length for the given data type.
  494. *
  495. * @method
  496. * @param {string} type - The data type.
  497. * @return {number} The length.
  498. */
  499. function getLengthFromType( type ) {
  500. if ( /float|int|uint/.test( type ) ) return 1;
  501. if ( /vec2/.test( type ) ) return 2;
  502. if ( /vec3/.test( type ) ) return 3;
  503. if ( /vec4/.test( type ) ) return 4;
  504. if ( /mat2/.test( type ) ) return 4;
  505. if ( /mat3/.test( type ) ) return 9;
  506. if ( /mat4/.test( type ) ) return 16;
  507. console.error( 'THREE.TSL: Unsupported type:', type );
  508. }
  509. /**
  510. * Returns the data type for the given value.
  511. *
  512. * @method
  513. * @param {any} value - The value.
  514. * @return {?string} The data type.
  515. */
  516. function getValueType( value ) {
  517. if ( value === undefined || value === null ) return null;
  518. const typeOf = typeof value;
  519. if ( value.isNode === true ) {
  520. return 'node';
  521. } else if ( typeOf === 'number' ) {
  522. return 'float';
  523. } else if ( typeOf === 'boolean' ) {
  524. return 'bool';
  525. } else if ( typeOf === 'string' ) {
  526. return 'string';
  527. } else if ( typeOf === 'function' ) {
  528. return 'shader';
  529. } else if ( value.isVector2 === true ) {
  530. return 'vec2';
  531. } else if ( value.isVector3 === true ) {
  532. return 'vec3';
  533. } else if ( value.isVector4 === true ) {
  534. return 'vec4';
  535. } else if ( value.isMatrix2 === true ) {
  536. return 'mat2';
  537. } else if ( value.isMatrix3 === true ) {
  538. return 'mat3';
  539. } else if ( value.isMatrix4 === true ) {
  540. return 'mat4';
  541. } else if ( value.isColor === true ) {
  542. return 'color';
  543. } else if ( value instanceof ArrayBuffer ) {
  544. return 'ArrayBuffer';
  545. }
  546. return null;
  547. }
  548. /**
  549. * Returns the value/object for the given data type and parameters.
  550. *
  551. * @method
  552. * @param {string} type - The given type.
  553. * @param {...any} params - A parameter list.
  554. * @return {any} The value/object.
  555. */
  556. function getValueFromType( type, ...params ) {
  557. const last4 = type ? type.slice( -4 ) : undefined;
  558. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  559. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  560. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  561. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  562. }
  563. if ( type === 'color' ) {
  564. return new Color( ...params );
  565. } else if ( last4 === 'vec2' ) {
  566. return new Vector2( ...params );
  567. } else if ( last4 === 'vec3' ) {
  568. return new Vector3( ...params );
  569. } else if ( last4 === 'vec4' ) {
  570. return new Vector4( ...params );
  571. } else if ( last4 === 'mat2' ) {
  572. return new Matrix2( ...params );
  573. } else if ( last4 === 'mat3' ) {
  574. return new Matrix3( ...params );
  575. } else if ( last4 === 'mat4' ) {
  576. return new Matrix4( ...params );
  577. } else if ( type === 'bool' ) {
  578. return params[ 0 ] || false;
  579. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  580. return params[ 0 ] || 0;
  581. } else if ( type === 'string' ) {
  582. return params[ 0 ] || '';
  583. } else if ( type === 'ArrayBuffer' ) {
  584. return base64ToArrayBuffer( params[ 0 ] );
  585. }
  586. return null;
  587. }
  588. /**
  589. * Gets the object data that can be shared between different rendering steps.
  590. *
  591. * @param {Object} object - The object to get the data for.
  592. * @return {Object} The object data.
  593. */
  594. function getDataFromObject( object ) {
  595. let data = dataFromObject.get( object );
  596. if ( data === undefined ) {
  597. data = {};
  598. dataFromObject.set( object, data );
  599. }
  600. return data;
  601. }
  602. /**
  603. * Converts the given array buffer to a Base64 string.
  604. *
  605. * @method
  606. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  607. * @return {string} The Base64 string.
  608. */
  609. function arrayBufferToBase64( arrayBuffer ) {
  610. let chars = '';
  611. const array = new Uint8Array( arrayBuffer );
  612. for ( let i = 0; i < array.length; i ++ ) {
  613. chars += String.fromCharCode( array[ i ] );
  614. }
  615. return btoa( chars );
  616. }
  617. /**
  618. * Converts the given Base64 string to an array buffer.
  619. *
  620. * @method
  621. * @param {string} base64 - The Base64 string.
  622. * @return {ArrayBuffer} The array buffer.
  623. */
  624. function base64ToArrayBuffer( base64 ) {
  625. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  626. }
  627. var NodeUtils = /*#__PURE__*/Object.freeze({
  628. __proto__: null,
  629. arrayBufferToBase64: arrayBufferToBase64,
  630. base64ToArrayBuffer: base64ToArrayBuffer,
  631. getCacheKey: getCacheKey$1,
  632. getDataFromObject: getDataFromObject,
  633. getLengthFromType: getLengthFromType,
  634. getNodeChildren: getNodeChildren,
  635. getTypeFromLength: getTypeFromLength,
  636. getTypedArrayFromType: getTypedArrayFromType,
  637. getValueFromType: getValueFromType,
  638. getValueType: getValueType,
  639. hash: hash$1,
  640. hashArray: hashArray,
  641. hashString: hashString
  642. });
  643. /**
  644. * Possible shader stages.
  645. *
  646. * @property {string} VERTEX The vertex shader stage.
  647. * @property {string} FRAGMENT The fragment shader stage.
  648. */
  649. const NodeShaderStage = {
  650. VERTEX: 'vertex',
  651. FRAGMENT: 'fragment'
  652. };
  653. /**
  654. * Update types of a node.
  655. *
  656. * @property {string} NONE The update method is not executed.
  657. * @property {string} FRAME The update method is executed per frame.
  658. * @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.
  659. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  660. */
  661. const NodeUpdateType = {
  662. NONE: 'none',
  663. FRAME: 'frame',
  664. RENDER: 'render',
  665. OBJECT: 'object'
  666. };
  667. /**
  668. * Data types of a node.
  669. *
  670. * @property {string} BOOLEAN Boolean type.
  671. * @property {string} INTEGER Integer type.
  672. * @property {string} FLOAT Float type.
  673. * @property {string} VECTOR2 Two-dimensional vector type.
  674. * @property {string} VECTOR3 Three-dimensional vector type.
  675. * @property {string} VECTOR4 Four-dimensional vector type.
  676. * @property {string} MATRIX2 2x2 matrix type.
  677. * @property {string} MATRIX3 3x3 matrix type.
  678. * @property {string} MATRIX4 4x4 matrix type.
  679. */
  680. const NodeType = {
  681. BOOLEAN: 'bool',
  682. INTEGER: 'int',
  683. FLOAT: 'float',
  684. VECTOR2: 'vec2',
  685. VECTOR3: 'vec3',
  686. VECTOR4: 'vec4',
  687. MATRIX2: 'mat2',
  688. MATRIX3: 'mat3',
  689. MATRIX4: 'mat4'
  690. };
  691. /**
  692. * Access types of a node. These are relevant for compute and storage usage.
  693. *
  694. * @property {string} READ_ONLY Read-only access
  695. * @property {string} WRITE_ONLY Write-only access.
  696. * @property {string} READ_WRITE Read and write access.
  697. */
  698. const NodeAccess = {
  699. READ_ONLY: 'readOnly',
  700. WRITE_ONLY: 'writeOnly',
  701. READ_WRITE: 'readWrite',
  702. };
  703. const defaultShaderStages = [ 'fragment', 'vertex' ];
  704. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  705. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  706. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  707. let _nodeId = 0;
  708. /**
  709. * Base class for all nodes.
  710. *
  711. * @augments EventDispatcher
  712. */
  713. class Node extends EventDispatcher {
  714. static get type() {
  715. return 'Node';
  716. }
  717. /**
  718. * Constructs a new node.
  719. *
  720. * @param {?string} nodeType - The node type.
  721. */
  722. constructor( nodeType = null ) {
  723. super();
  724. /**
  725. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  726. *
  727. * @type {?string}
  728. * @default null
  729. */
  730. this.nodeType = nodeType;
  731. /**
  732. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  733. *
  734. * @type {string}
  735. * @default 'none'
  736. */
  737. this.updateType = NodeUpdateType.NONE;
  738. /**
  739. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  740. *
  741. * @type {string}
  742. * @default 'none'
  743. */
  744. this.updateBeforeType = NodeUpdateType.NONE;
  745. /**
  746. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  747. *
  748. * @type {string}
  749. * @default 'none'
  750. */
  751. this.updateAfterType = NodeUpdateType.NONE;
  752. /**
  753. * The UUID of the node.
  754. *
  755. * @type {string}
  756. * @readonly
  757. */
  758. this.uuid = MathUtils.generateUUID();
  759. /**
  760. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  761. *
  762. * @type {number}
  763. * @readonly
  764. * @default 0
  765. */
  766. this.version = 0;
  767. /**
  768. * Whether this node is global or not. This property is relevant for the internal
  769. * node caching system. All nodes which should be declared just once should
  770. * set this flag to `true` (a typical example is {@link AttributeNode}).
  771. *
  772. * @type {boolean}
  773. * @default false
  774. */
  775. this.global = false;
  776. /**
  777. * This flag can be used for type testing.
  778. *
  779. * @type {boolean}
  780. * @readonly
  781. * @default true
  782. */
  783. this.isNode = true;
  784. // private
  785. /**
  786. * The cache key of this node.
  787. *
  788. * @private
  789. * @type {?number}
  790. * @default null
  791. */
  792. this._cacheKey = null;
  793. /**
  794. * The cache key 's version.
  795. *
  796. * @private
  797. * @type {number}
  798. * @default 0
  799. */
  800. this._cacheKeyVersion = 0;
  801. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  802. }
  803. /**
  804. * Set this property to `true` when the node should be regenerated.
  805. *
  806. * @type {boolean}
  807. * @default false
  808. * @param {boolean} value
  809. */
  810. set needsUpdate( value ) {
  811. if ( value === true ) {
  812. this.version ++;
  813. }
  814. }
  815. /**
  816. * The type of the class. The value is usually the constructor name.
  817. *
  818. * @type {string}
  819. * @readonly
  820. */
  821. get type() {
  822. return this.constructor.type;
  823. }
  824. /**
  825. * Convenient method for defining {@link Node#update}.
  826. *
  827. * @param {Function} callback - The update method.
  828. * @param {string} updateType - The update type.
  829. * @return {Node} A reference to this node.
  830. */
  831. onUpdate( callback, updateType ) {
  832. this.updateType = updateType;
  833. this.update = callback.bind( this.getSelf() );
  834. return this;
  835. }
  836. /**
  837. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  838. * this method automatically sets the update type to `FRAME`.
  839. *
  840. * @param {Function} callback - The update method.
  841. * @return {Node} A reference to this node.
  842. */
  843. onFrameUpdate( callback ) {
  844. return this.onUpdate( callback, NodeUpdateType.FRAME );
  845. }
  846. /**
  847. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  848. * this method automatically sets the update type to `RENDER`.
  849. *
  850. * @param {Function} callback - The update method.
  851. * @return {Node} A reference to this node.
  852. */
  853. onRenderUpdate( callback ) {
  854. return this.onUpdate( callback, NodeUpdateType.RENDER );
  855. }
  856. /**
  857. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  858. * this method automatically sets the update type to `OBJECT`.
  859. *
  860. * @param {Function} callback - The update method.
  861. * @return {Node} A reference to this node.
  862. */
  863. onObjectUpdate( callback ) {
  864. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  865. }
  866. /**
  867. * Convenient method for defining {@link Node#updateReference}.
  868. *
  869. * @param {Function} callback - The update method.
  870. * @return {Node} A reference to this node.
  871. */
  872. onReference( callback ) {
  873. this.updateReference = callback.bind( this.getSelf() );
  874. return this;
  875. }
  876. /**
  877. * The `this` reference might point to a Proxy so this method can be used
  878. * to get the reference to the actual node instance.
  879. *
  880. * @return {Node} A reference to the node.
  881. */
  882. getSelf() {
  883. // Returns non-node object.
  884. return this.self || this;
  885. }
  886. /**
  887. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  888. * to such objects based on a given state (e.g. the current node frame or builder).
  889. *
  890. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  891. * @return {any} The updated reference.
  892. */
  893. updateReference( /*state*/ ) {
  894. return this;
  895. }
  896. /**
  897. * By default this method returns the value of the {@link Node#global} flag. This method
  898. * can be overwritten in derived classes if an analytical way is required to determine the
  899. * global status.
  900. *
  901. * @param {NodeBuilder} builder - The current node builder.
  902. * @return {boolean} Whether this node is global or not.
  903. */
  904. isGlobal( /*builder*/ ) {
  905. return this.global;
  906. }
  907. /**
  908. * Generator function that can be used to iterate over the child nodes.
  909. *
  910. * @generator
  911. * @yields {Node} A child node.
  912. */
  913. * getChildren() {
  914. for ( const { childNode } of getNodeChildren( this ) ) {
  915. yield childNode;
  916. }
  917. }
  918. /**
  919. * Calling this method dispatches the `dispose` event. This event can be used
  920. * to register event listeners for clean up tasks.
  921. */
  922. dispose() {
  923. this.dispatchEvent( { type: 'dispose' } );
  924. }
  925. /**
  926. * Callback for {@link Node#traverse}.
  927. *
  928. * @callback traverseCallback
  929. * @param {Node} node - The current node.
  930. */
  931. /**
  932. * Can be used to traverse through the node's hierarchy.
  933. *
  934. * @param {traverseCallback} callback - A callback that is executed per node.
  935. */
  936. traverse( callback ) {
  937. callback( this );
  938. for ( const childNode of this.getChildren() ) {
  939. childNode.traverse( callback );
  940. }
  941. }
  942. /**
  943. * Returns the cache key for this node.
  944. *
  945. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  946. * @return {number} The cache key of the node.
  947. */
  948. getCacheKey( force = false ) {
  949. force = force || this.version !== this._cacheKeyVersion;
  950. if ( force === true || this._cacheKey === null ) {
  951. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  952. this._cacheKeyVersion = this.version;
  953. }
  954. return this._cacheKey;
  955. }
  956. /**
  957. * Generate a custom cache key for this node.
  958. *
  959. * @return {number} The cache key of the node.
  960. */
  961. customCacheKey() {
  962. return 0;
  963. }
  964. /**
  965. * Returns the references to this node which is by default `this`.
  966. *
  967. * @return {Node} A reference to this node.
  968. */
  969. getScope() {
  970. return this;
  971. }
  972. /**
  973. * Returns the hash of the node which is used to identify the node. By default it's
  974. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  975. * depending on their implementation.
  976. *
  977. * @param {NodeBuilder} builder - The current node builder.
  978. * @return {string} The hash.
  979. */
  980. getHash( /*builder*/ ) {
  981. return this.uuid;
  982. }
  983. /**
  984. * Returns the update type of {@link Node#update}.
  985. *
  986. * @return {NodeUpdateType} The update type.
  987. */
  988. getUpdateType() {
  989. return this.updateType;
  990. }
  991. /**
  992. * Returns the update type of {@link Node#updateBefore}.
  993. *
  994. * @return {NodeUpdateType} The update type.
  995. */
  996. getUpdateBeforeType() {
  997. return this.updateBeforeType;
  998. }
  999. /**
  1000. * Returns the update type of {@link Node#updateAfter}.
  1001. *
  1002. * @return {NodeUpdateType} The update type.
  1003. */
  1004. getUpdateAfterType() {
  1005. return this.updateAfterType;
  1006. }
  1007. /**
  1008. * Certain types are composed of multiple elements. For example a `vec3`
  1009. * is composed of three `float` values. This method returns the type of
  1010. * these elements.
  1011. *
  1012. * @param {NodeBuilder} builder - The current node builder.
  1013. * @return {string} The type of the node.
  1014. */
  1015. getElementType( builder ) {
  1016. const type = this.getNodeType( builder );
  1017. const elementType = builder.getElementType( type );
  1018. return elementType;
  1019. }
  1020. /**
  1021. * Returns the node member type for the given name.
  1022. *
  1023. * @param {NodeBuilder} builder - The current node builder.
  1024. * @param {string} name - The name of the member.
  1025. * @return {string} The type of the node.
  1026. */
  1027. getMemberType( /*builder, name*/ ) {
  1028. return 'void';
  1029. }
  1030. /**
  1031. * Returns the node's type.
  1032. *
  1033. * @param {NodeBuilder} builder - The current node builder.
  1034. * @return {string} The type of the node.
  1035. */
  1036. getNodeType( builder ) {
  1037. const nodeProperties = builder.getNodeProperties( this );
  1038. if ( nodeProperties.outputNode ) {
  1039. return nodeProperties.outputNode.getNodeType( builder );
  1040. }
  1041. return this.nodeType;
  1042. }
  1043. /**
  1044. * This method is used during the build process of a node and ensures
  1045. * equal nodes are not built multiple times but just once. For example if
  1046. * `attribute( 'uv' )` is used multiple times by the user, the build
  1047. * process makes sure to process just the first node.
  1048. *
  1049. * @param {NodeBuilder} builder - The current node builder.
  1050. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1051. */
  1052. getShared( builder ) {
  1053. const hash = this.getHash( builder );
  1054. const nodeFromHash = builder.getNodeFromHash( hash );
  1055. return nodeFromHash || this;
  1056. }
  1057. /**
  1058. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1059. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1060. * The output node must be returned in the `return` statement.
  1061. *
  1062. * @param {NodeBuilder} builder - The current node builder.
  1063. * @return {?Node} The output node.
  1064. */
  1065. setup( builder ) {
  1066. const nodeProperties = builder.getNodeProperties( this );
  1067. let index = 0;
  1068. for ( const childNode of this.getChildren() ) {
  1069. nodeProperties[ 'node' + index ++ ] = childNode;
  1070. }
  1071. // return a outputNode if exists or null
  1072. return nodeProperties.outputNode || null;
  1073. }
  1074. /**
  1075. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1076. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1077. *
  1078. * @param {NodeBuilder} builder - The current node builder.
  1079. */
  1080. analyze( builder ) {
  1081. const usageCount = builder.increaseUsage( this );
  1082. if ( usageCount === 1 ) {
  1083. // node flow children
  1084. const nodeProperties = builder.getNodeProperties( this );
  1085. for ( const childNode of Object.values( nodeProperties ) ) {
  1086. if ( childNode && childNode.isNode === true ) {
  1087. childNode.build( builder );
  1088. }
  1089. }
  1090. }
  1091. }
  1092. /**
  1093. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1094. * This state builds the output node and returns the resulting shader string.
  1095. *
  1096. * @param {NodeBuilder} builder - The current node builder.
  1097. * @param {?string} output - Can be used to define the output type.
  1098. * @return {?string} The generated shader string.
  1099. */
  1100. generate( builder, output ) {
  1101. const { outputNode } = builder.getNodeProperties( this );
  1102. if ( outputNode && outputNode.isNode === true ) {
  1103. return outputNode.build( builder, output );
  1104. }
  1105. }
  1106. /**
  1107. * The method can be implemented to update the node's internal state before it is used to render an object.
  1108. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1109. *
  1110. * @abstract
  1111. * @param {NodeFrame} frame - A reference to the current node frame.
  1112. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1113. */
  1114. updateBefore( /*frame*/ ) {
  1115. console.warn( 'Abstract function.' );
  1116. }
  1117. /**
  1118. * The method can be implemented to update the node's internal state after it was used to render an object.
  1119. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1120. *
  1121. * @abstract
  1122. * @param {NodeFrame} frame - A reference to the current node frame.
  1123. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1124. */
  1125. updateAfter( /*frame*/ ) {
  1126. console.warn( 'Abstract function.' );
  1127. }
  1128. /**
  1129. * The method can be implemented to update the node's internal state when it is used to render an object.
  1130. * The {@link Node#updateType} property defines how often the update is executed.
  1131. *
  1132. * @abstract
  1133. * @param {NodeFrame} frame - A reference to the current node frame.
  1134. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1135. */
  1136. update( /*frame*/ ) {
  1137. console.warn( 'Abstract function.' );
  1138. }
  1139. /**
  1140. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1141. * on the current build stage (setup, analyze or generate).
  1142. *
  1143. * @param {NodeBuilder} builder - The current node builder.
  1144. * @param {?string} output - Can be used to define the output type.
  1145. * @return {?string} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1146. */
  1147. build( builder, output = null ) {
  1148. const refNode = this.getShared( builder );
  1149. if ( this !== refNode ) {
  1150. return refNode.build( builder, output );
  1151. }
  1152. builder.addNode( this );
  1153. builder.addChain( this );
  1154. /* Build stages expected results:
  1155. - "setup" -> Node
  1156. - "analyze" -> null
  1157. - "generate" -> String
  1158. */
  1159. let result = null;
  1160. const buildStage = builder.getBuildStage();
  1161. if ( buildStage === 'setup' ) {
  1162. this.updateReference( builder );
  1163. const properties = builder.getNodeProperties( this );
  1164. if ( properties.initialized !== true ) {
  1165. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1166. properties.initialized = true;
  1167. const outputNode = this.setup( builder ); // return a node or null
  1168. const isNodeOutput = outputNode && outputNode.isNode === true;
  1169. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1170. // !! no outputNode !!
  1171. //outputNode = builder.stack;
  1172. }*/
  1173. for ( const childNode of Object.values( properties ) ) {
  1174. if ( childNode && childNode.isNode === true ) {
  1175. childNode.build( builder );
  1176. }
  1177. }
  1178. if ( isNodeOutput ) {
  1179. outputNode.build( builder );
  1180. }
  1181. properties.outputNode = outputNode;
  1182. }
  1183. } else if ( buildStage === 'analyze' ) {
  1184. this.analyze( builder );
  1185. } else if ( buildStage === 'generate' ) {
  1186. const isGenerateOnce = this.generate.length === 1;
  1187. if ( isGenerateOnce ) {
  1188. const type = this.getNodeType( builder );
  1189. const nodeData = builder.getDataFromNode( this );
  1190. result = nodeData.snippet;
  1191. if ( result === undefined ) {
  1192. result = this.generate( builder ) || '';
  1193. nodeData.snippet = result;
  1194. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1195. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1196. }
  1197. result = builder.format( result, type, output );
  1198. } else {
  1199. result = this.generate( builder, output ) || '';
  1200. }
  1201. }
  1202. builder.removeChain( this );
  1203. builder.addSequentialNode( this );
  1204. return result;
  1205. }
  1206. /**
  1207. * Returns the child nodes as a JSON object.
  1208. *
  1209. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1210. */
  1211. getSerializeChildren() {
  1212. return getNodeChildren( this );
  1213. }
  1214. /**
  1215. * Serializes the node to JSON.
  1216. *
  1217. * @param {Object} json - The output JSON object.
  1218. */
  1219. serialize( json ) {
  1220. const nodeChildren = this.getSerializeChildren();
  1221. const inputNodes = {};
  1222. for ( const { property, index, childNode } of nodeChildren ) {
  1223. if ( index !== undefined ) {
  1224. if ( inputNodes[ property ] === undefined ) {
  1225. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1226. }
  1227. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1228. } else {
  1229. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1230. }
  1231. }
  1232. if ( Object.keys( inputNodes ).length > 0 ) {
  1233. json.inputNodes = inputNodes;
  1234. }
  1235. }
  1236. /**
  1237. * Deserializes the node from the given JSON.
  1238. *
  1239. * @param {Object} json - The JSON object.
  1240. */
  1241. deserialize( json ) {
  1242. if ( json.inputNodes !== undefined ) {
  1243. const nodes = json.meta.nodes;
  1244. for ( const property in json.inputNodes ) {
  1245. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1246. const inputArray = [];
  1247. for ( const uuid of json.inputNodes[ property ] ) {
  1248. inputArray.push( nodes[ uuid ] );
  1249. }
  1250. this[ property ] = inputArray;
  1251. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1252. const inputObject = {};
  1253. for ( const subProperty in json.inputNodes[ property ] ) {
  1254. const uuid = json.inputNodes[ property ][ subProperty ];
  1255. inputObject[ subProperty ] = nodes[ uuid ];
  1256. }
  1257. this[ property ] = inputObject;
  1258. } else {
  1259. const uuid = json.inputNodes[ property ];
  1260. this[ property ] = nodes[ uuid ];
  1261. }
  1262. }
  1263. }
  1264. }
  1265. /**
  1266. * Serializes the node into the three.js JSON Object/Scene format.
  1267. *
  1268. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1269. * @return {Object} The serialized node.
  1270. */
  1271. toJSON( meta ) {
  1272. const { uuid, type } = this;
  1273. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1274. if ( isRoot ) {
  1275. meta = {
  1276. textures: {},
  1277. images: {},
  1278. nodes: {}
  1279. };
  1280. }
  1281. // serialize
  1282. let data = meta.nodes[ uuid ];
  1283. if ( data === undefined ) {
  1284. data = {
  1285. uuid,
  1286. type,
  1287. meta,
  1288. metadata: {
  1289. version: 4.6,
  1290. type: 'Node',
  1291. generator: 'Node.toJSON'
  1292. }
  1293. };
  1294. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1295. this.serialize( data );
  1296. delete data.meta;
  1297. }
  1298. // TODO: Copied from Object3D.toJSON
  1299. function extractFromCache( cache ) {
  1300. const values = [];
  1301. for ( const key in cache ) {
  1302. const data = cache[ key ];
  1303. delete data.metadata;
  1304. values.push( data );
  1305. }
  1306. return values;
  1307. }
  1308. if ( isRoot ) {
  1309. const textures = extractFromCache( meta.textures );
  1310. const images = extractFromCache( meta.images );
  1311. const nodes = extractFromCache( meta.nodes );
  1312. if ( textures.length > 0 ) data.textures = textures;
  1313. if ( images.length > 0 ) data.images = images;
  1314. if ( nodes.length > 0 ) data.nodes = nodes;
  1315. }
  1316. return data;
  1317. }
  1318. }
  1319. /**
  1320. * Base class for representing element access on an array-like
  1321. * node data structures.
  1322. *
  1323. * @augments Node
  1324. */
  1325. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1326. static get type() {
  1327. return 'ArrayElementNode';
  1328. }
  1329. /**
  1330. * Constructs an array element node.
  1331. *
  1332. * @param {Node} node - The array-like node.
  1333. * @param {Node} indexNode - The index node that defines the element access.
  1334. */
  1335. constructor( node, indexNode ) {
  1336. super();
  1337. /**
  1338. * The array-like node.
  1339. *
  1340. * @type {Node}
  1341. */
  1342. this.node = node;
  1343. /**
  1344. * The index node that defines the element access.
  1345. *
  1346. * @type {Node}
  1347. */
  1348. this.indexNode = indexNode;
  1349. /**
  1350. * This flag can be used for type testing.
  1351. *
  1352. * @type {boolean}
  1353. * @readonly
  1354. * @default true
  1355. */
  1356. this.isArrayElementNode = true;
  1357. }
  1358. /**
  1359. * This method is overwritten since the node type is inferred from the array-like node.
  1360. *
  1361. * @param {NodeBuilder} builder - The current node builder.
  1362. * @return {string} The node type.
  1363. */
  1364. getNodeType( builder ) {
  1365. return this.node.getElementType( builder );
  1366. }
  1367. generate( builder ) {
  1368. const nodeSnippet = this.node.build( builder );
  1369. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1370. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1371. }
  1372. }
  1373. /**
  1374. * This module is part of the TSL core and usually not used in app level code.
  1375. * It represents a convert operation during the shader generation process
  1376. * meaning it converts the data type of a node to a target data type.
  1377. *
  1378. * @augments Node
  1379. */
  1380. class ConvertNode extends Node {
  1381. static get type() {
  1382. return 'ConvertNode';
  1383. }
  1384. /**
  1385. * Constructs a new convert node.
  1386. *
  1387. * @param {Node} node - The node which type should be converted.
  1388. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1389. */
  1390. constructor( node, convertTo ) {
  1391. super();
  1392. /**
  1393. * The node which type should be converted.
  1394. *
  1395. * @type {Node}
  1396. */
  1397. this.node = node;
  1398. /**
  1399. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1400. *
  1401. * @type {string}
  1402. */
  1403. this.convertTo = convertTo;
  1404. }
  1405. /**
  1406. * This method is overwritten since the implementation tries to infer the best
  1407. * matching type from the {@link ConvertNode#convertTo} property.
  1408. *
  1409. * @param {NodeBuilder} builder - The current node builder.
  1410. * @return {string} The node type.
  1411. */
  1412. getNodeType( builder ) {
  1413. const requestType = this.node.getNodeType( builder );
  1414. let convertTo = null;
  1415. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1416. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1417. convertTo = overloadingType;
  1418. }
  1419. }
  1420. return convertTo;
  1421. }
  1422. serialize( data ) {
  1423. super.serialize( data );
  1424. data.convertTo = this.convertTo;
  1425. }
  1426. deserialize( data ) {
  1427. super.deserialize( data );
  1428. this.convertTo = data.convertTo;
  1429. }
  1430. generate( builder, output ) {
  1431. const node = this.node;
  1432. const type = this.getNodeType( builder );
  1433. const snippet = node.build( builder, type );
  1434. return builder.format( snippet, type, output );
  1435. }
  1436. }
  1437. /**
  1438. * This module uses cache management to create temporary variables
  1439. * if the node is used more than once to prevent duplicate calculations.
  1440. *
  1441. * The class acts as a base class for many other nodes types.
  1442. *
  1443. * @augments Node
  1444. */
  1445. class TempNode extends Node {
  1446. static get type() {
  1447. return 'TempNode';
  1448. }
  1449. /**
  1450. * Constructs a temp node.
  1451. *
  1452. * @param {?string} nodeType - The node type.
  1453. */
  1454. constructor( nodeType = null ) {
  1455. super( nodeType );
  1456. /**
  1457. * This flag can be used for type testing.
  1458. *
  1459. * @type {boolean}
  1460. * @readonly
  1461. * @default true
  1462. */
  1463. this.isTempNode = true;
  1464. }
  1465. /**
  1466. * Whether this node is used more than once in context of other nodes.
  1467. *
  1468. * @param {NodeBuilder} builder - The node builder.
  1469. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1470. */
  1471. hasDependencies( builder ) {
  1472. return builder.getDataFromNode( this ).usageCount > 1;
  1473. }
  1474. build( builder, output ) {
  1475. const buildStage = builder.getBuildStage();
  1476. if ( buildStage === 'generate' ) {
  1477. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1478. const nodeData = builder.getDataFromNode( this );
  1479. if ( nodeData.propertyName !== undefined ) {
  1480. return builder.format( nodeData.propertyName, type, output );
  1481. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1482. const snippet = super.build( builder, type );
  1483. const nodeVar = builder.getVarFromNode( this, null, type );
  1484. const propertyName = builder.getPropertyName( nodeVar );
  1485. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1486. nodeData.snippet = snippet;
  1487. nodeData.propertyName = propertyName;
  1488. return builder.format( nodeData.propertyName, type, output );
  1489. }
  1490. }
  1491. return super.build( builder, output );
  1492. }
  1493. }
  1494. /**
  1495. * This module is part of the TSL core and usually not used in app level code.
  1496. * It represents a join operation during the shader generation process.
  1497. * For example in can compose/join two single floats into a `vec2` type.
  1498. *
  1499. * @augments TempNode
  1500. */
  1501. class JoinNode extends TempNode {
  1502. static get type() {
  1503. return 'JoinNode';
  1504. }
  1505. /**
  1506. * Constructs a new join node.
  1507. *
  1508. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1509. * @param {?string} [nodeType=null] - The node type.
  1510. */
  1511. constructor( nodes = [], nodeType = null ) {
  1512. super( nodeType );
  1513. /**
  1514. * An array of nodes that should be joined.
  1515. *
  1516. * @type {Array<Node>}
  1517. */
  1518. this.nodes = nodes;
  1519. }
  1520. /**
  1521. * This method is overwritten since the node type must be inferred from the
  1522. * joined data length if not explicitly defined.
  1523. *
  1524. * @param {NodeBuilder} builder - The current node builder.
  1525. * @return {string} The node type.
  1526. */
  1527. getNodeType( builder ) {
  1528. if ( this.nodeType !== null ) {
  1529. return builder.getVectorType( this.nodeType );
  1530. }
  1531. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1532. }
  1533. generate( builder, output ) {
  1534. const type = this.getNodeType( builder );
  1535. const nodes = this.nodes;
  1536. const primitiveType = builder.getComponentType( type );
  1537. const snippetValues = [];
  1538. for ( const input of nodes ) {
  1539. let inputSnippet = input.build( builder );
  1540. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1541. if ( inputPrimitiveType !== primitiveType ) {
  1542. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1543. }
  1544. snippetValues.push( inputSnippet );
  1545. }
  1546. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1547. return builder.format( snippet, type, output );
  1548. }
  1549. }
  1550. const _stringVectorComponents = vectorComponents.join( '' );
  1551. /**
  1552. * This module is part of the TSL core and usually not used in app level code.
  1553. * `SplitNode` represents a property access operation which means it is
  1554. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1555. * For example:
  1556. * ```js
  1557. * const redValue = color.r;
  1558. * ```
  1559. *
  1560. * @augments Node
  1561. */
  1562. class SplitNode extends Node {
  1563. static get type() {
  1564. return 'SplitNode';
  1565. }
  1566. /**
  1567. * Constructs a new split node.
  1568. *
  1569. * @param {Node} node - The node that should be accessed.
  1570. * @param {string} [components='x'] - The components that should be accessed.
  1571. */
  1572. constructor( node, components = 'x' ) {
  1573. super();
  1574. /**
  1575. * The node that should be accessed.
  1576. *
  1577. * @type {Node}
  1578. */
  1579. this.node = node;
  1580. /**
  1581. * The components that should be accessed.
  1582. *
  1583. * @type {string}
  1584. */
  1585. this.components = components;
  1586. /**
  1587. * This flag can be used for type testing.
  1588. *
  1589. * @type {boolean}
  1590. * @readonly
  1591. * @default true
  1592. */
  1593. this.isSplitNode = true;
  1594. }
  1595. /**
  1596. * Returns the vector length which is computed based on the requested components.
  1597. *
  1598. * @return {number} The vector length.
  1599. */
  1600. getVectorLength() {
  1601. let vectorLength = this.components.length;
  1602. for ( const c of this.components ) {
  1603. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1604. }
  1605. return vectorLength;
  1606. }
  1607. /**
  1608. * Returns the component type of the node's type.
  1609. *
  1610. * @param {NodeBuilder} builder - The current node builder.
  1611. * @return {string} The component type.
  1612. */
  1613. getComponentType( builder ) {
  1614. return builder.getComponentType( this.node.getNodeType( builder ) );
  1615. }
  1616. /**
  1617. * This method is overwritten since the node type is inferred from requested components.
  1618. *
  1619. * @param {NodeBuilder} builder - The current node builder.
  1620. * @return {string} The node type.
  1621. */
  1622. getNodeType( builder ) {
  1623. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1624. }
  1625. generate( builder, output ) {
  1626. const node = this.node;
  1627. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1628. let snippet = null;
  1629. if ( nodeTypeLength > 1 ) {
  1630. let type = null;
  1631. const componentsLength = this.getVectorLength();
  1632. if ( componentsLength >= nodeTypeLength ) {
  1633. // needed expand the input node
  1634. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1635. }
  1636. const nodeSnippet = node.build( builder, type );
  1637. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1638. // unnecessary swizzle
  1639. snippet = builder.format( nodeSnippet, type, output );
  1640. } else {
  1641. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1642. }
  1643. } else {
  1644. // ignore .components if .node returns float/integer
  1645. snippet = node.build( builder, output );
  1646. }
  1647. return snippet;
  1648. }
  1649. serialize( data ) {
  1650. super.serialize( data );
  1651. data.components = this.components;
  1652. }
  1653. deserialize( data ) {
  1654. super.deserialize( data );
  1655. this.components = data.components;
  1656. }
  1657. }
  1658. /**
  1659. * This module is part of the TSL core and usually not used in app level code.
  1660. * `SetNode` represents a set operation which means it is used to implement any
  1661. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1662. * For example:
  1663. * ```js
  1664. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1665. * ```
  1666. *
  1667. * @augments TempNode
  1668. */
  1669. class SetNode extends TempNode {
  1670. static get type() {
  1671. return 'SetNode';
  1672. }
  1673. /**
  1674. * Constructs a new set node.
  1675. *
  1676. * @param {Node} sourceNode - The node that should be updated.
  1677. * @param {string} components - The components that should be updated.
  1678. * @param {Node} targetNode - The value node.
  1679. */
  1680. constructor( sourceNode, components, targetNode ) {
  1681. super();
  1682. /**
  1683. * The node that should be updated.
  1684. *
  1685. * @type {Node}
  1686. */
  1687. this.sourceNode = sourceNode;
  1688. /**
  1689. * The components that should be updated.
  1690. *
  1691. * @type {string}
  1692. */
  1693. this.components = components;
  1694. /**
  1695. * The value node.
  1696. *
  1697. * @type {Node}
  1698. */
  1699. this.targetNode = targetNode;
  1700. }
  1701. /**
  1702. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1703. *
  1704. * @param {NodeBuilder} builder - The current node builder.
  1705. * @return {string} The node type.
  1706. */
  1707. getNodeType( builder ) {
  1708. return this.sourceNode.getNodeType( builder );
  1709. }
  1710. generate( builder ) {
  1711. const { sourceNode, components, targetNode } = this;
  1712. const sourceType = this.getNodeType( builder );
  1713. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1714. const targetType = builder.getTypeFromLength( components.length, componentType );
  1715. const targetSnippet = targetNode.build( builder, targetType );
  1716. const sourceSnippet = sourceNode.build( builder, sourceType );
  1717. const length = builder.getTypeLength( sourceType );
  1718. const snippetValues = [];
  1719. for ( let i = 0; i < length; i ++ ) {
  1720. const component = vectorComponents[ i ];
  1721. if ( component === components[ 0 ] ) {
  1722. snippetValues.push( targetSnippet );
  1723. i += components.length - 1;
  1724. } else {
  1725. snippetValues.push( sourceSnippet + '.' + component );
  1726. }
  1727. }
  1728. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1729. }
  1730. }
  1731. /**
  1732. * This module is part of the TSL core and usually not used in app level code.
  1733. * It represents a flip operation during the shader generation process
  1734. * meaning it flips normalized values with the following formula:
  1735. * ```
  1736. * x = 1 - x;
  1737. * ```
  1738. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1739. * `flipSTPQ()` method invocations on node objects. For example:
  1740. * ```js
  1741. * uvNode = uvNode.flipY();
  1742. * ```
  1743. *
  1744. * @augments TempNode
  1745. */
  1746. class FlipNode extends TempNode {
  1747. static get type() {
  1748. return 'FlipNode';
  1749. }
  1750. /**
  1751. * Constructs a new flip node.
  1752. *
  1753. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1754. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1755. */
  1756. constructor( sourceNode, components ) {
  1757. super();
  1758. /**
  1759. * The node which component(s) should be flipped.
  1760. *
  1761. * @type {Node}
  1762. */
  1763. this.sourceNode = sourceNode;
  1764. /**
  1765. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1766. *
  1767. * @type {string}
  1768. */
  1769. this.components = components;
  1770. }
  1771. /**
  1772. * This method is overwritten since the node type is inferred from the source node.
  1773. *
  1774. * @param {NodeBuilder} builder - The current node builder.
  1775. * @return {string} The node type.
  1776. */
  1777. getNodeType( builder ) {
  1778. return this.sourceNode.getNodeType( builder );
  1779. }
  1780. generate( builder ) {
  1781. const { components, sourceNode } = this;
  1782. const sourceType = this.getNodeType( builder );
  1783. const sourceSnippet = sourceNode.build( builder );
  1784. const sourceCache = builder.getVarFromNode( this );
  1785. const sourceProperty = builder.getPropertyName( sourceCache );
  1786. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1787. const length = builder.getTypeLength( sourceType );
  1788. const snippetValues = [];
  1789. let componentIndex = 0;
  1790. for ( let i = 0; i < length; i ++ ) {
  1791. const component = vectorComponents[ i ];
  1792. if ( component === components[ componentIndex ] ) {
  1793. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1794. componentIndex ++;
  1795. } else {
  1796. snippetValues.push( sourceProperty + '.' + component );
  1797. }
  1798. }
  1799. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1800. }
  1801. }
  1802. /**
  1803. * Base class for representing data input nodes.
  1804. *
  1805. * @augments Node
  1806. */
  1807. class InputNode extends Node {
  1808. static get type() {
  1809. return 'InputNode';
  1810. }
  1811. /**
  1812. * Constructs a new input node.
  1813. *
  1814. * @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).
  1815. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1816. */
  1817. constructor( value, nodeType = null ) {
  1818. super( nodeType );
  1819. /**
  1820. * This flag can be used for type testing.
  1821. *
  1822. * @type {boolean}
  1823. * @readonly
  1824. * @default true
  1825. */
  1826. this.isInputNode = true;
  1827. /**
  1828. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1829. *
  1830. * @type {any}
  1831. */
  1832. this.value = value;
  1833. /**
  1834. * The precision of the value in the shader.
  1835. *
  1836. * @type {?('low'|'medium'|'high')}
  1837. * @default null
  1838. */
  1839. this.precision = null;
  1840. }
  1841. getNodeType( /*builder*/ ) {
  1842. if ( this.nodeType === null ) {
  1843. return getValueType( this.value );
  1844. }
  1845. return this.nodeType;
  1846. }
  1847. /**
  1848. * Returns the input type of the node which is by default the node type. Derived modules
  1849. * might overwrite this method and use a fixed type or compute one analytically.
  1850. *
  1851. * A typical example for different input and node types are textures. The input type of a
  1852. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1853. *
  1854. * @param {NodeBuilder} builder - The current node builder.
  1855. * @return {string} The input type.
  1856. */
  1857. getInputType( builder ) {
  1858. return this.getNodeType( builder );
  1859. }
  1860. /**
  1861. * Sets the precision to the given value. The method can be
  1862. * overwritten in derived classes if the final precision must be computed
  1863. * analytically.
  1864. *
  1865. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1866. * @return {InputNode} A reference to this node.
  1867. */
  1868. setPrecision( precision ) {
  1869. this.precision = precision;
  1870. return this;
  1871. }
  1872. serialize( data ) {
  1873. super.serialize( data );
  1874. data.value = this.value;
  1875. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1876. data.valueType = getValueType( this.value );
  1877. data.nodeType = this.nodeType;
  1878. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1879. data.precision = this.precision;
  1880. }
  1881. deserialize( data ) {
  1882. super.deserialize( data );
  1883. this.nodeType = data.nodeType;
  1884. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1885. this.precision = data.precision || null;
  1886. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1887. }
  1888. generate( /*builder, output*/ ) {
  1889. console.warn( 'Abstract function.' );
  1890. }
  1891. }
  1892. const _regNum = /float|u?int/;
  1893. /**
  1894. * Class for representing a constant value in the shader.
  1895. *
  1896. * @augments InputNode
  1897. */
  1898. class ConstNode extends InputNode {
  1899. static get type() {
  1900. return 'ConstNode';
  1901. }
  1902. /**
  1903. * Constructs a new input node.
  1904. *
  1905. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1906. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1907. */
  1908. constructor( value, nodeType = null ) {
  1909. super( value, nodeType );
  1910. /**
  1911. * This flag can be used for type testing.
  1912. *
  1913. * @type {boolean}
  1914. * @readonly
  1915. * @default true
  1916. */
  1917. this.isConstNode = true;
  1918. }
  1919. /**
  1920. * Generates the shader string of the value with the current node builder.
  1921. *
  1922. * @param {NodeBuilder} builder - The current node builder.
  1923. * @return {string} The generated value as a shader string.
  1924. */
  1925. generateConst( builder ) {
  1926. return builder.generateConst( this.getNodeType( builder ), this.value );
  1927. }
  1928. generate( builder, output ) {
  1929. const type = this.getNodeType( builder );
  1930. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  1931. return builder.generateConst( output, this.value );
  1932. }
  1933. return builder.format( this.generateConst( builder ), type, output );
  1934. }
  1935. }
  1936. /**
  1937. * Base class for representing member access on an object-like
  1938. * node data structures.
  1939. *
  1940. * @augments Node
  1941. */
  1942. class MemberNode extends Node {
  1943. static get type() {
  1944. return 'MemberNode';
  1945. }
  1946. /**
  1947. * Constructs an array element node.
  1948. *
  1949. * @param {Node} node - The array-like node.
  1950. * @param {string} property - The property name.
  1951. */
  1952. constructor( node, property ) {
  1953. super();
  1954. /**
  1955. * The array-like node.
  1956. *
  1957. * @type {Node}
  1958. */
  1959. this.node = node;
  1960. /**
  1961. * The property name.
  1962. *
  1963. * @type {Node}
  1964. */
  1965. this.property = property;
  1966. /**
  1967. * This flag can be used for type testing.
  1968. *
  1969. * @type {boolean}
  1970. * @readonly
  1971. * @default true
  1972. */
  1973. this.isMemberNode = true;
  1974. }
  1975. getNodeType( builder ) {
  1976. return this.node.getMemberType( builder, this.property );
  1977. }
  1978. generate( builder ) {
  1979. const propertyName = this.node.build( builder );
  1980. return propertyName + '.' + this.property;
  1981. }
  1982. }
  1983. let currentStack = null;
  1984. const NodeElements = new Map();
  1985. function addMethodChaining( name, nodeElement ) {
  1986. if ( NodeElements.has( name ) ) {
  1987. console.warn( `Redefinition of method chaining ${ name }` );
  1988. return;
  1989. }
  1990. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1991. NodeElements.set( name, nodeElement );
  1992. }
  1993. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1994. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1995. const shaderNodeHandler = {
  1996. setup( NodeClosure, params ) {
  1997. const inputs = params.shift();
  1998. return NodeClosure( nodeObjects( inputs ), ...params );
  1999. },
  2000. get( node, prop, nodeObj ) {
  2001. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2002. if ( node.isStackNode !== true && prop === 'assign' ) {
  2003. return ( ...params ) => {
  2004. currentStack.assign( nodeObj, ...params );
  2005. return nodeObj;
  2006. };
  2007. } else if ( NodeElements.has( prop ) ) {
  2008. const nodeElement = NodeElements.get( prop );
  2009. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2010. } else if ( prop === 'self' ) {
  2011. return node;
  2012. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2013. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2014. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2015. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2016. // accessing properties ( swizzle )
  2017. prop = parseSwizzle( prop );
  2018. return nodeObject( new SplitNode( nodeObj, prop ) );
  2019. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2020. // set properties ( swizzle ) and sort to xyzw sequence
  2021. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2022. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  2023. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2024. // set properties ( swizzle ) and sort to xyzw sequence
  2025. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2026. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2027. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2028. // accessing property
  2029. if ( prop === 'width' ) prop = 'x';
  2030. else if ( prop === 'height' ) prop = 'y';
  2031. else if ( prop === 'depth' ) prop = 'z';
  2032. return nodeObject( new SplitNode( node, prop ) );
  2033. } else if ( /^\d+$/.test( prop ) === true ) {
  2034. // accessing array
  2035. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2036. } else if ( /^get$/.test( prop ) === true ) {
  2037. // accessing properties
  2038. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2039. }
  2040. }
  2041. return Reflect.get( node, prop, nodeObj );
  2042. },
  2043. set( node, prop, value, nodeObj ) {
  2044. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2045. // setting properties
  2046. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2047. nodeObj[ prop ].assign( value );
  2048. return true;
  2049. }
  2050. }
  2051. return Reflect.set( node, prop, value, nodeObj );
  2052. }
  2053. };
  2054. const nodeObjectsCacheMap = new WeakMap();
  2055. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2056. const ShaderNodeObject = function ( obj, altType = null ) {
  2057. const type = getValueType( obj );
  2058. if ( type === 'node' ) {
  2059. let nodeObject = nodeObjectsCacheMap.get( obj );
  2060. if ( nodeObject === undefined ) {
  2061. nodeObject = new Proxy( obj, shaderNodeHandler );
  2062. nodeObjectsCacheMap.set( obj, nodeObject );
  2063. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2064. }
  2065. return nodeObject;
  2066. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2067. return nodeObject( getConstNode( obj, altType ) );
  2068. } else if ( type === 'shader' ) {
  2069. return Fn( obj );
  2070. }
  2071. return obj;
  2072. };
  2073. const ShaderNodeObjects = function ( objects, altType = null ) {
  2074. for ( const name in objects ) {
  2075. objects[ name ] = nodeObject( objects[ name ], altType );
  2076. }
  2077. return objects;
  2078. };
  2079. const ShaderNodeArray = function ( array, altType = null ) {
  2080. const len = array.length;
  2081. for ( let i = 0; i < len; i ++ ) {
  2082. array[ i ] = nodeObject( array[ i ], altType );
  2083. }
  2084. return array;
  2085. };
  2086. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2087. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2088. if ( scope === null ) {
  2089. return ( ...params ) => {
  2090. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2091. };
  2092. } else if ( factor !== null ) {
  2093. factor = nodeObject( factor );
  2094. return ( ...params ) => {
  2095. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2096. };
  2097. } else {
  2098. return ( ...params ) => {
  2099. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2100. };
  2101. }
  2102. };
  2103. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2104. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2105. };
  2106. class ShaderCallNodeInternal extends Node {
  2107. constructor( shaderNode, inputNodes ) {
  2108. super();
  2109. this.shaderNode = shaderNode;
  2110. this.inputNodes = inputNodes;
  2111. }
  2112. getNodeType( builder ) {
  2113. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2114. }
  2115. getMemberType( builder, name ) {
  2116. return this.getOutputNode( builder ).getMemberType( builder, name );
  2117. }
  2118. call( builder ) {
  2119. const { shaderNode, inputNodes } = this;
  2120. const properties = builder.getNodeProperties( shaderNode );
  2121. if ( properties.onceOutput ) return properties.onceOutput;
  2122. //
  2123. let result = null;
  2124. if ( shaderNode.layout ) {
  2125. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2126. if ( functionNodesCacheMap === undefined ) {
  2127. functionNodesCacheMap = new WeakMap();
  2128. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2129. }
  2130. let functionNode = functionNodesCacheMap.get( shaderNode );
  2131. if ( functionNode === undefined ) {
  2132. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2133. functionNodesCacheMap.set( shaderNode, functionNode );
  2134. }
  2135. builder.addInclude( functionNode );
  2136. result = nodeObject( functionNode.call( inputNodes ) );
  2137. } else {
  2138. const jsFunc = shaderNode.jsFunc;
  2139. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2140. result = nodeObject( outputNode );
  2141. }
  2142. if ( shaderNode.once ) {
  2143. properties.onceOutput = result;
  2144. }
  2145. return result;
  2146. }
  2147. getOutputNode( builder ) {
  2148. const properties = builder.getNodeProperties( this );
  2149. if ( properties.outputNode === null ) {
  2150. properties.outputNode = this.setupOutput( builder );
  2151. }
  2152. return properties.outputNode;
  2153. }
  2154. setup( builder ) {
  2155. return this.getOutputNode( builder );
  2156. }
  2157. setupOutput( builder ) {
  2158. builder.addStack();
  2159. builder.stack.outputNode = this.call( builder );
  2160. return builder.removeStack();
  2161. }
  2162. generate( builder, output ) {
  2163. const outputNode = this.getOutputNode( builder );
  2164. return outputNode.build( builder, output );
  2165. }
  2166. }
  2167. class ShaderNodeInternal extends Node {
  2168. constructor( jsFunc, nodeType ) {
  2169. super( nodeType );
  2170. this.jsFunc = jsFunc;
  2171. this.layout = null;
  2172. this.global = true;
  2173. this.once = false;
  2174. }
  2175. setLayout( layout ) {
  2176. this.layout = layout;
  2177. return this;
  2178. }
  2179. call( inputs = null ) {
  2180. nodeObjects( inputs );
  2181. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2182. }
  2183. setup() {
  2184. return this.call();
  2185. }
  2186. }
  2187. const bools = [ false, true ];
  2188. const uints = [ 0, 1, 2, 3 ];
  2189. const ints = [ -1, -2 ];
  2190. 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 ];
  2191. const boolsCacheMap = new Map();
  2192. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2193. const uintsCacheMap = new Map();
  2194. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2195. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2196. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2197. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2198. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2199. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2200. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2201. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2202. const getConstNode = ( value, type ) => {
  2203. if ( constNodesCacheMap.has( value ) ) {
  2204. return constNodesCacheMap.get( value );
  2205. } else if ( value.isNode === true ) {
  2206. return value;
  2207. } else {
  2208. return new ConstNode( value, type );
  2209. }
  2210. };
  2211. const safeGetNodeType = ( node ) => {
  2212. try {
  2213. return node.getNodeType();
  2214. } catch ( _ ) {
  2215. return undefined;
  2216. }
  2217. };
  2218. const ConvertType = function ( type, cacheMap = null ) {
  2219. return ( ...params ) => {
  2220. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2221. params = [ getValueFromType( type, ...params ) ];
  2222. }
  2223. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2224. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2225. }
  2226. if ( params.length === 1 ) {
  2227. const node = getConstNode( params[ 0 ], type );
  2228. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2229. return nodeObject( new ConvertNode( node, type ) );
  2230. }
  2231. const nodes = params.map( param => getConstNode( param ) );
  2232. return nodeObject( new JoinNode( nodes, type ) );
  2233. };
  2234. };
  2235. // exports
  2236. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2237. // utils
  2238. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2239. // shader node base
  2240. function ShaderNode( jsFunc, nodeType ) {
  2241. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2242. }
  2243. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2244. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2245. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2246. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2247. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2248. const Fn = ( jsFunc, nodeType ) => {
  2249. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2250. const fn = ( ...params ) => {
  2251. let inputs;
  2252. nodeObjects( params );
  2253. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2254. inputs = [ ...params ];
  2255. } else {
  2256. inputs = params[ 0 ];
  2257. }
  2258. return shaderNode.call( inputs );
  2259. };
  2260. fn.shaderNode = shaderNode;
  2261. fn.setLayout = ( layout ) => {
  2262. shaderNode.setLayout( layout );
  2263. return fn;
  2264. };
  2265. fn.once = () => {
  2266. shaderNode.once = true;
  2267. return fn;
  2268. };
  2269. return fn;
  2270. };
  2271. /**
  2272. * @tsl
  2273. * @function
  2274. * @deprecated since r168. Use {@link Fn} instead.
  2275. *
  2276. * @param {...any} params
  2277. * @returns {Function}
  2278. */
  2279. const tslFn = ( ...params ) => { // @deprecated, r168
  2280. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2281. return Fn( ...params );
  2282. };
  2283. //
  2284. addMethodChaining( 'toGlobal', ( node ) => {
  2285. node.global = true;
  2286. return node;
  2287. } );
  2288. //
  2289. const setCurrentStack = ( stack ) => {
  2290. currentStack = stack;
  2291. };
  2292. const getCurrentStack = () => currentStack;
  2293. const If = ( ...params ) => currentStack.If( ...params );
  2294. function append( node ) {
  2295. if ( currentStack ) currentStack.add( node );
  2296. return node;
  2297. }
  2298. addMethodChaining( 'append', append );
  2299. // types
  2300. const color = new ConvertType( 'color' );
  2301. const float = new ConvertType( 'float', cacheMaps.float );
  2302. const int = new ConvertType( 'int', cacheMaps.ints );
  2303. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2304. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2305. const vec2 = new ConvertType( 'vec2' );
  2306. const ivec2 = new ConvertType( 'ivec2' );
  2307. const uvec2 = new ConvertType( 'uvec2' );
  2308. const bvec2 = new ConvertType( 'bvec2' );
  2309. const vec3 = new ConvertType( 'vec3' );
  2310. const ivec3 = new ConvertType( 'ivec3' );
  2311. const uvec3 = new ConvertType( 'uvec3' );
  2312. const bvec3 = new ConvertType( 'bvec3' );
  2313. const vec4 = new ConvertType( 'vec4' );
  2314. const ivec4 = new ConvertType( 'ivec4' );
  2315. const uvec4 = new ConvertType( 'uvec4' );
  2316. const bvec4 = new ConvertType( 'bvec4' );
  2317. const mat2 = new ConvertType( 'mat2' );
  2318. const mat3 = new ConvertType( 'mat3' );
  2319. const mat4 = new ConvertType( 'mat4' );
  2320. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2321. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2322. addMethodChaining( 'toColor', color );
  2323. addMethodChaining( 'toFloat', float );
  2324. addMethodChaining( 'toInt', int );
  2325. addMethodChaining( 'toUint', uint );
  2326. addMethodChaining( 'toBool', bool );
  2327. addMethodChaining( 'toVec2', vec2 );
  2328. addMethodChaining( 'toIVec2', ivec2 );
  2329. addMethodChaining( 'toUVec2', uvec2 );
  2330. addMethodChaining( 'toBVec2', bvec2 );
  2331. addMethodChaining( 'toVec3', vec3 );
  2332. addMethodChaining( 'toIVec3', ivec3 );
  2333. addMethodChaining( 'toUVec3', uvec3 );
  2334. addMethodChaining( 'toBVec3', bvec3 );
  2335. addMethodChaining( 'toVec4', vec4 );
  2336. addMethodChaining( 'toIVec4', ivec4 );
  2337. addMethodChaining( 'toUVec4', uvec4 );
  2338. addMethodChaining( 'toBVec4', bvec4 );
  2339. addMethodChaining( 'toMat2', mat2 );
  2340. addMethodChaining( 'toMat3', mat3 );
  2341. addMethodChaining( 'toMat4', mat4 );
  2342. // basic nodes
  2343. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2344. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2345. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2346. addMethodChaining( 'element', element );
  2347. addMethodChaining( 'convert', convert );
  2348. /**
  2349. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  2350. * ```js
  2351. * const colors = array( [
  2352. * vec3( 1, 0, 0 ),
  2353. * vec3( 0, 1, 0 ),
  2354. * vec3( 0, 0, 1 )
  2355. * ] );
  2356. *
  2357. * const redColor = tintColors.element( 0 );
  2358. *
  2359. * @augments TempNode
  2360. */
  2361. class ArrayNode extends TempNode {
  2362. static get type() {
  2363. return 'ArrayNode';
  2364. }
  2365. /**
  2366. * Constructs a new array node.
  2367. *
  2368. * @param {?string} nodeType - The data type of the elements.
  2369. * @param {number} count - Size of the array.
  2370. * @param {?Array<Node>} [values=null] - Array default values.
  2371. */
  2372. constructor( nodeType, count, values = null ) {
  2373. super( nodeType );
  2374. /**
  2375. * Array size.
  2376. *
  2377. * @type {number}
  2378. */
  2379. this.count = count;
  2380. /**
  2381. * Array default values.
  2382. *
  2383. * @type {?Array<Node>}
  2384. */
  2385. this.values = values;
  2386. /**
  2387. * This flag can be used for type testing.
  2388. *
  2389. * @type {boolean}
  2390. * @readonly
  2391. * @default true
  2392. */
  2393. this.isArrayNode = true;
  2394. }
  2395. /**
  2396. * Returns the node's type.
  2397. *
  2398. * @param {NodeBuilder} builder - The current node builder.
  2399. * @return {string} The type of the node.
  2400. */
  2401. getNodeType( builder ) {
  2402. if ( this.nodeType === null ) {
  2403. this.nodeType = this.values[ 0 ].getNodeType( builder );
  2404. }
  2405. return this.nodeType;
  2406. }
  2407. /**
  2408. * Returns the node's type.
  2409. *
  2410. * @param {NodeBuilder} builder - The current node builder.
  2411. * @return {string} The type of the node.
  2412. */
  2413. getElementType( builder ) {
  2414. return this.getNodeType( builder );
  2415. }
  2416. /**
  2417. * This method builds the output node and returns the resulting array as a shader string.
  2418. *
  2419. * @param {NodeBuilder} builder - The current node builder.
  2420. * @return {string} The generated shader string.
  2421. */
  2422. generate( builder ) {
  2423. const type = this.getNodeType( builder );
  2424. return builder.generateArray( type, this.count, this.values );
  2425. }
  2426. }
  2427. /**
  2428. * TSL function for creating an array node.
  2429. *
  2430. * @tsl
  2431. * @function
  2432. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  2433. * or an array containing the default values (e.g., [ vec3() ]).
  2434. * @param {?number} [count] - Size of the array.
  2435. * @returns {ArrayNode}
  2436. */
  2437. const array = ( ...params ) => {
  2438. let node;
  2439. if ( params.length === 1 ) {
  2440. const values = params[ 0 ];
  2441. node = new ArrayNode( null, values.length, values );
  2442. } else {
  2443. const nodeType = params[ 0 ];
  2444. const count = params[ 1 ];
  2445. node = new ArrayNode( nodeType, count );
  2446. }
  2447. return nodeObject( node );
  2448. };
  2449. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  2450. /**
  2451. * This node can be used to group single instances of {@link UniformNode}
  2452. * and manage them as a uniform buffer.
  2453. *
  2454. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2455. * will be used when defining the {@link UniformNode#groupNode} property.
  2456. *
  2457. * - `objectGroup`: Uniform buffer per object.
  2458. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2459. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2460. *
  2461. * @augments Node
  2462. */
  2463. class UniformGroupNode extends Node {
  2464. static get type() {
  2465. return 'UniformGroupNode';
  2466. }
  2467. /**
  2468. * Constructs a new uniform group node.
  2469. *
  2470. * @param {string} name - The name of the uniform group node.
  2471. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2472. * @param {number} [order=1] - Influences the internal sorting.
  2473. */
  2474. constructor( name, shared = false, order = 1 ) {
  2475. super( 'string' );
  2476. /**
  2477. * The name of the uniform group node.
  2478. *
  2479. * @type {string}
  2480. */
  2481. this.name = name;
  2482. /**
  2483. * Whether this uniform group node is shared or not.
  2484. *
  2485. * @type {boolean}
  2486. * @default false
  2487. */
  2488. this.shared = shared;
  2489. /**
  2490. * Influences the internal sorting.
  2491. * TODO: Add details when this property should be changed.
  2492. *
  2493. * @type {number}
  2494. * @default 1
  2495. */
  2496. this.order = order;
  2497. /**
  2498. * This flag can be used for type testing.
  2499. *
  2500. * @type {boolean}
  2501. * @readonly
  2502. * @default true
  2503. */
  2504. this.isUniformGroup = true;
  2505. }
  2506. serialize( data ) {
  2507. super.serialize( data );
  2508. data.name = this.name;
  2509. data.version = this.version;
  2510. data.shared = this.shared;
  2511. }
  2512. deserialize( data ) {
  2513. super.deserialize( data );
  2514. this.name = data.name;
  2515. this.version = data.version;
  2516. this.shared = data.shared;
  2517. }
  2518. }
  2519. /**
  2520. * TSL function for creating a uniform group node with the given name.
  2521. *
  2522. * @tsl
  2523. * @function
  2524. * @param {string} name - The name of the uniform group node.
  2525. * @returns {UniformGroupNode}
  2526. */
  2527. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2528. /**
  2529. * TSL function for creating a shared uniform group node with the given name and order.
  2530. *
  2531. * @tsl
  2532. * @function
  2533. * @param {string} name - The name of the uniform group node.
  2534. * @param {number} [order=0] - Influences the internal sorting.
  2535. * @returns {UniformGroupNode}
  2536. */
  2537. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2538. /**
  2539. * TSL object that represents a shared uniform group node which is updated once per frame.
  2540. *
  2541. * @tsl
  2542. * @type {UniformGroupNode}
  2543. */
  2544. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2545. /**
  2546. * TSL object that represents a shared uniform group node which is updated once per render.
  2547. *
  2548. * @tsl
  2549. * @type {UniformGroupNode}
  2550. */
  2551. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2552. /**
  2553. * TSL object that represents a uniform group node which is updated once per object.
  2554. *
  2555. * @tsl
  2556. * @type {UniformGroupNode}
  2557. */
  2558. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2559. /**
  2560. * Class for representing a uniform.
  2561. *
  2562. * @augments InputNode
  2563. */
  2564. class UniformNode extends InputNode {
  2565. static get type() {
  2566. return 'UniformNode';
  2567. }
  2568. /**
  2569. * Constructs a new uniform node.
  2570. *
  2571. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2572. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2573. */
  2574. constructor( value, nodeType = null ) {
  2575. super( value, nodeType );
  2576. /**
  2577. * This flag can be used for type testing.
  2578. *
  2579. * @type {boolean}
  2580. * @readonly
  2581. * @default true
  2582. */
  2583. this.isUniformNode = true;
  2584. /**
  2585. * The name or label of the uniform.
  2586. *
  2587. * @type {string}
  2588. * @default ''
  2589. */
  2590. this.name = '';
  2591. /**
  2592. * The uniform group of this uniform. By default, uniforms are
  2593. * managed per object but they might belong to a shared group
  2594. * which is updated per frame or render call.
  2595. *
  2596. * @type {UniformGroupNode}
  2597. */
  2598. this.groupNode = objectGroup;
  2599. }
  2600. /**
  2601. * Sets the {@link UniformNode#name} property.
  2602. *
  2603. * @param {string} name - The name of the uniform.
  2604. * @return {UniformNode} A reference to this node.
  2605. */
  2606. label( name ) {
  2607. this.name = name;
  2608. return this;
  2609. }
  2610. /**
  2611. * Sets the {@link UniformNode#groupNode} property.
  2612. *
  2613. * @param {UniformGroupNode} group - The uniform group.
  2614. * @return {UniformNode} A reference to this node.
  2615. */
  2616. setGroup( group ) {
  2617. this.groupNode = group;
  2618. return this;
  2619. }
  2620. /**
  2621. * Returns the {@link UniformNode#groupNode}.
  2622. *
  2623. * @return {UniformGroupNode} The uniform group.
  2624. */
  2625. getGroup() {
  2626. return this.groupNode;
  2627. }
  2628. /**
  2629. * By default, this method returns the result of {@link Node#getHash} but derived
  2630. * classes might overwrite this method with a different implementation.
  2631. *
  2632. * @param {NodeBuilder} builder - The current node builder.
  2633. * @return {string} The uniform hash.
  2634. */
  2635. getUniformHash( builder ) {
  2636. return this.getHash( builder );
  2637. }
  2638. onUpdate( callback, updateType ) {
  2639. const self = this.getSelf();
  2640. callback = callback.bind( self );
  2641. return super.onUpdate( ( frame ) => {
  2642. const value = callback( frame, self );
  2643. if ( value !== undefined ) {
  2644. this.value = value;
  2645. }
  2646. }, updateType );
  2647. }
  2648. generate( builder, output ) {
  2649. const type = this.getNodeType( builder );
  2650. const hash = this.getUniformHash( builder );
  2651. let sharedNode = builder.getNodeFromHash( hash );
  2652. if ( sharedNode === undefined ) {
  2653. builder.setHashNode( this, hash );
  2654. sharedNode = this;
  2655. }
  2656. const sharedNodeType = sharedNode.getInputType( builder );
  2657. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2658. const propertyName = builder.getPropertyName( nodeUniform );
  2659. if ( builder.context.label !== undefined ) delete builder.context.label;
  2660. return builder.format( propertyName, type, output );
  2661. }
  2662. }
  2663. /**
  2664. * TSL function for creating a uniform node.
  2665. *
  2666. * @tsl
  2667. * @function
  2668. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2669. * @param {string} [arg2] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2670. * @returns {UniformNode}
  2671. */
  2672. const uniform = ( arg1, arg2 ) => {
  2673. const nodeType = getConstNodeType( arg2 || arg1 );
  2674. // @TODO: get ConstNode from .traverse() in the future
  2675. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2676. return nodeObject( new UniformNode( value, nodeType ) );
  2677. };
  2678. /**
  2679. * This class represents a shader property. It can be used
  2680. * to explicitly define a property and assign a value to it.
  2681. *
  2682. * ```js
  2683. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2684. *```
  2685. * `PropertyNode` is used by the engine to predefined common material properties
  2686. * for TSL code.
  2687. *
  2688. * @augments Node
  2689. */
  2690. class PropertyNode extends Node {
  2691. static get type() {
  2692. return 'PropertyNode';
  2693. }
  2694. /**
  2695. * Constructs a new property node.
  2696. *
  2697. * @param {string} nodeType - The type of the node.
  2698. * @param {?string} [name=null] - The name of the property in the shader.
  2699. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2700. */
  2701. constructor( nodeType, name = null, varying = false ) {
  2702. super( nodeType );
  2703. /**
  2704. * The name of the property in the shader. If no name is defined,
  2705. * the node system auto-generates one.
  2706. *
  2707. * @type {?string}
  2708. * @default null
  2709. */
  2710. this.name = name;
  2711. /**
  2712. * Whether this property is a varying or not.
  2713. *
  2714. * @type {boolean}
  2715. * @default false
  2716. */
  2717. this.varying = varying;
  2718. /**
  2719. * This flag can be used for type testing.
  2720. *
  2721. * @type {boolean}
  2722. * @readonly
  2723. * @default true
  2724. */
  2725. this.isPropertyNode = true;
  2726. }
  2727. getHash( builder ) {
  2728. return this.name || super.getHash( builder );
  2729. }
  2730. /**
  2731. * The method is overwritten so it always returns `true`.
  2732. *
  2733. * @param {NodeBuilder} builder - The current node builder.
  2734. * @return {boolean} Whether this node is global or not.
  2735. */
  2736. isGlobal( /*builder*/ ) {
  2737. return true;
  2738. }
  2739. generate( builder ) {
  2740. let nodeVar;
  2741. if ( this.varying === true ) {
  2742. nodeVar = builder.getVaryingFromNode( this, this.name );
  2743. nodeVar.needsInterpolation = true;
  2744. } else {
  2745. nodeVar = builder.getVarFromNode( this, this.name );
  2746. }
  2747. return builder.getPropertyName( nodeVar );
  2748. }
  2749. }
  2750. /**
  2751. * TSL function for creating a property node.
  2752. *
  2753. * @tsl
  2754. * @function
  2755. * @param {string} type - The type of the node.
  2756. * @param {?string} [name=null] - The name of the property in the shader.
  2757. * @returns {PropertyNode}
  2758. */
  2759. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2760. /**
  2761. * TSL function for creating a varying property node.
  2762. *
  2763. * @tsl
  2764. * @function
  2765. * @param {string} type - The type of the node.
  2766. * @param {?string} [name=null] - The name of the varying in the shader.
  2767. * @returns {PropertyNode}
  2768. */
  2769. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2770. /**
  2771. * TSL object that represents the shader variable `DiffuseColor`.
  2772. *
  2773. * @tsl
  2774. * @type {PropertyNode<vec4>}
  2775. */
  2776. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2777. /**
  2778. * TSL object that represents the shader variable `EmissiveColor`.
  2779. *
  2780. * @tsl
  2781. * @type {PropertyNode<vec3>}
  2782. */
  2783. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2784. /**
  2785. * TSL object that represents the shader variable `Roughness`.
  2786. *
  2787. * @tsl
  2788. * @type {PropertyNode<float>}
  2789. */
  2790. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2791. /**
  2792. * TSL object that represents the shader variable `Metalness`.
  2793. *
  2794. * @tsl
  2795. * @type {PropertyNode<float>}
  2796. */
  2797. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2798. /**
  2799. * TSL object that represents the shader variable `Clearcoat`.
  2800. *
  2801. * @tsl
  2802. * @type {PropertyNode<float>}
  2803. */
  2804. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2805. /**
  2806. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2807. *
  2808. * @tsl
  2809. * @type {PropertyNode<float>}
  2810. */
  2811. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2812. /**
  2813. * TSL object that represents the shader variable `Sheen`.
  2814. *
  2815. * @tsl
  2816. * @type {PropertyNode<vec3>}
  2817. */
  2818. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2819. /**
  2820. * TSL object that represents the shader variable `SheenRoughness`.
  2821. *
  2822. * @tsl
  2823. * @type {PropertyNode<float>}
  2824. */
  2825. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2826. /**
  2827. * TSL object that represents the shader variable `Iridescence`.
  2828. *
  2829. * @tsl
  2830. * @type {PropertyNode<float>}
  2831. */
  2832. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2833. /**
  2834. * TSL object that represents the shader variable `IridescenceIOR`.
  2835. *
  2836. * @tsl
  2837. * @type {PropertyNode<float>}
  2838. */
  2839. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2840. /**
  2841. * TSL object that represents the shader variable `IridescenceThickness`.
  2842. *
  2843. * @tsl
  2844. * @type {PropertyNode<float>}
  2845. */
  2846. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2847. /**
  2848. * TSL object that represents the shader variable `AlphaT`.
  2849. *
  2850. * @tsl
  2851. * @type {PropertyNode<float>}
  2852. */
  2853. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2854. /**
  2855. * TSL object that represents the shader variable `Anisotropy`.
  2856. *
  2857. * @tsl
  2858. * @type {PropertyNode<float>}
  2859. */
  2860. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2861. /**
  2862. * TSL object that represents the shader variable `AnisotropyT`.
  2863. *
  2864. * @tsl
  2865. * @type {PropertyNode<vec3>}
  2866. */
  2867. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2868. /**
  2869. * TSL object that represents the shader variable `AnisotropyB`.
  2870. *
  2871. * @tsl
  2872. * @type {PropertyNode<vec3>}
  2873. */
  2874. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2875. /**
  2876. * TSL object that represents the shader variable `SpecularColor`.
  2877. *
  2878. * @tsl
  2879. * @type {PropertyNode<color>}
  2880. */
  2881. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2882. /**
  2883. * TSL object that represents the shader variable `SpecularF90`.
  2884. *
  2885. * @tsl
  2886. * @type {PropertyNode<float>}
  2887. */
  2888. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2889. /**
  2890. * TSL object that represents the shader variable `Shininess`.
  2891. *
  2892. * @tsl
  2893. * @type {PropertyNode<float>}
  2894. */
  2895. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2896. /**
  2897. * TSL object that represents the shader variable `Output`.
  2898. *
  2899. * @tsl
  2900. * @type {PropertyNode<vec4>}
  2901. */
  2902. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2903. /**
  2904. * TSL object that represents the shader variable `dashSize`.
  2905. *
  2906. * @tsl
  2907. * @type {PropertyNode<float>}
  2908. */
  2909. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2910. /**
  2911. * TSL object that represents the shader variable `gapSize`.
  2912. *
  2913. * @tsl
  2914. * @type {PropertyNode<float>}
  2915. */
  2916. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2917. /**
  2918. * TSL object that represents the shader variable `pointWidth`.
  2919. *
  2920. * @tsl
  2921. * @type {PropertyNode<float>}
  2922. */
  2923. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2924. /**
  2925. * TSL object that represents the shader variable `IOR`.
  2926. *
  2927. * @tsl
  2928. * @type {PropertyNode<float>}
  2929. */
  2930. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2931. /**
  2932. * TSL object that represents the shader variable `Transmission`.
  2933. *
  2934. * @tsl
  2935. * @type {PropertyNode<float>}
  2936. */
  2937. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2938. /**
  2939. * TSL object that represents the shader variable `Thickness`.
  2940. *
  2941. * @tsl
  2942. * @type {PropertyNode<float>}
  2943. */
  2944. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2945. /**
  2946. * TSL object that represents the shader variable `AttenuationDistance`.
  2947. *
  2948. * @tsl
  2949. * @type {PropertyNode<float>}
  2950. */
  2951. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2952. /**
  2953. * TSL object that represents the shader variable `AttenuationColor`.
  2954. *
  2955. * @tsl
  2956. * @type {PropertyNode<color>}
  2957. */
  2958. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2959. /**
  2960. * TSL object that represents the shader variable `Dispersion`.
  2961. *
  2962. * @tsl
  2963. * @type {PropertyNode<float>}
  2964. */
  2965. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2966. /**
  2967. * These node represents an assign operation. Meaning a node is assigned
  2968. * to another node.
  2969. *
  2970. * @augments TempNode
  2971. */
  2972. class AssignNode extends TempNode {
  2973. static get type() {
  2974. return 'AssignNode';
  2975. }
  2976. /**
  2977. * Constructs a new assign node.
  2978. *
  2979. * @param {Node} targetNode - The target node.
  2980. * @param {Node} sourceNode - The source type.
  2981. */
  2982. constructor( targetNode, sourceNode ) {
  2983. super();
  2984. /**
  2985. * The target node.
  2986. *
  2987. * @type {Node}
  2988. */
  2989. this.targetNode = targetNode;
  2990. /**
  2991. * The source node.
  2992. *
  2993. * @type {Node}
  2994. */
  2995. this.sourceNode = sourceNode;
  2996. }
  2997. /**
  2998. * Whether this node is used more than once in context of other nodes. This method
  2999. * is overwritten since it always returns `false` (assigns are unique).
  3000. *
  3001. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3002. */
  3003. hasDependencies() {
  3004. return false;
  3005. }
  3006. getNodeType( builder, output ) {
  3007. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3008. }
  3009. /**
  3010. * Whether a split is required when assigning source to target. This can happen when the component length of
  3011. * target and source data type does not match.
  3012. *
  3013. * @param {NodeBuilder} builder - The current node builder.
  3014. * @return {boolean} Whether a split is required when assigning source to target.
  3015. */
  3016. needsSplitAssign( builder ) {
  3017. const { targetNode } = this;
  3018. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3019. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3020. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3021. return assignDifferentVector;
  3022. }
  3023. return false;
  3024. }
  3025. generate( builder, output ) {
  3026. const { targetNode, sourceNode } = this;
  3027. const needsSplitAssign = this.needsSplitAssign( builder );
  3028. const targetType = targetNode.getNodeType( builder );
  3029. const target = targetNode.context( { assign: true } ).build( builder );
  3030. const source = sourceNode.build( builder, targetType );
  3031. const sourceType = sourceNode.getNodeType( builder );
  3032. const nodeData = builder.getDataFromNode( this );
  3033. //
  3034. let snippet;
  3035. if ( nodeData.initialized === true ) {
  3036. if ( output !== 'void' ) {
  3037. snippet = target;
  3038. }
  3039. } else if ( needsSplitAssign ) {
  3040. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3041. const sourceProperty = builder.getPropertyName( sourceVar );
  3042. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3043. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  3044. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  3045. const component = targetNode.components[ i ];
  3046. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3047. }
  3048. if ( output !== 'void' ) {
  3049. snippet = target;
  3050. }
  3051. } else {
  3052. snippet = `${ target } = ${ source }`;
  3053. if ( output === 'void' || sourceType === 'void' ) {
  3054. builder.addLineFlowCode( snippet, this );
  3055. if ( output !== 'void' ) {
  3056. snippet = target;
  3057. }
  3058. }
  3059. }
  3060. nodeData.initialized = true;
  3061. return builder.format( snippet, targetType, output );
  3062. }
  3063. }
  3064. /**
  3065. * TSL function for creating an assign node.
  3066. *
  3067. * @tsl
  3068. * @function
  3069. * @param {Node} targetNode - The target node.
  3070. * @param {Node} sourceNode - The source type.
  3071. * @returns {AssignNode}
  3072. */
  3073. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  3074. addMethodChaining( 'assign', assign );
  3075. /**
  3076. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3077. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3078. * this logic.
  3079. *
  3080. * @augments TempNode
  3081. */
  3082. class FunctionCallNode extends TempNode {
  3083. static get type() {
  3084. return 'FunctionCallNode';
  3085. }
  3086. /**
  3087. * Constructs a new function call node.
  3088. *
  3089. * @param {?FunctionNode} functionNode - The function node.
  3090. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3091. */
  3092. constructor( functionNode = null, parameters = {} ) {
  3093. super();
  3094. /**
  3095. * The function node.
  3096. *
  3097. * @type {?FunctionNode}
  3098. * @default null
  3099. */
  3100. this.functionNode = functionNode;
  3101. /**
  3102. * The parameters of the function call.
  3103. *
  3104. * @type {Object<string, Node>}
  3105. * @default {}
  3106. */
  3107. this.parameters = parameters;
  3108. }
  3109. /**
  3110. * Sets the parameters of the function call node.
  3111. *
  3112. * @param {Object<string, Node>} parameters - The parameters to set.
  3113. * @return {FunctionCallNode} A reference to this node.
  3114. */
  3115. setParameters( parameters ) {
  3116. this.parameters = parameters;
  3117. return this;
  3118. }
  3119. /**
  3120. * Returns the parameters of the function call node.
  3121. *
  3122. * @return {Object<string, Node>} The parameters of this node.
  3123. */
  3124. getParameters() {
  3125. return this.parameters;
  3126. }
  3127. getNodeType( builder ) {
  3128. return this.functionNode.getNodeType( builder );
  3129. }
  3130. generate( builder ) {
  3131. const params = [];
  3132. const functionNode = this.functionNode;
  3133. const inputs = functionNode.getInputs( builder );
  3134. const parameters = this.parameters;
  3135. const generateInput = ( node, inputNode ) => {
  3136. const type = inputNode.type;
  3137. const pointer = type === 'pointer';
  3138. let output;
  3139. if ( pointer ) output = '&' + node.build( builder );
  3140. else output = node.build( builder, type );
  3141. return output;
  3142. };
  3143. if ( Array.isArray( parameters ) ) {
  3144. for ( let i = 0; i < parameters.length; i ++ ) {
  3145. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3146. }
  3147. } else {
  3148. for ( const inputNode of inputs ) {
  3149. const node = parameters[ inputNode.name ];
  3150. if ( node !== undefined ) {
  3151. params.push( generateInput( node, inputNode ) );
  3152. } else {
  3153. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  3154. }
  3155. }
  3156. }
  3157. const functionName = functionNode.build( builder, 'property' );
  3158. return `${functionName}( ${params.join( ', ' )} )`;
  3159. }
  3160. }
  3161. const call = ( func, ...params ) => {
  3162. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3163. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3164. };
  3165. addMethodChaining( 'call', call );
  3166. /**
  3167. * This node represents basic mathematical and logical operations like addition,
  3168. * subtraction or comparisons (e.g. `equal()`).
  3169. *
  3170. * @augments TempNode
  3171. */
  3172. class OperatorNode extends TempNode {
  3173. static get type() {
  3174. return 'OperatorNode';
  3175. }
  3176. /**
  3177. * Constructs a new operator node.
  3178. *
  3179. * @param {string} op - The operator.
  3180. * @param {Node} aNode - The first input.
  3181. * @param {Node} bNode - The second input.
  3182. * @param {...Node} params - Additional input parameters.
  3183. */
  3184. constructor( op, aNode, bNode, ...params ) {
  3185. super();
  3186. if ( params.length > 0 ) {
  3187. let finalOp = new OperatorNode( op, aNode, bNode );
  3188. for ( let i = 0; i < params.length - 1; i ++ ) {
  3189. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3190. }
  3191. aNode = finalOp;
  3192. bNode = params[ params.length - 1 ];
  3193. }
  3194. /**
  3195. * The operator.
  3196. *
  3197. * @type {string}
  3198. */
  3199. this.op = op;
  3200. /**
  3201. * The first input.
  3202. *
  3203. * @type {Node}
  3204. */
  3205. this.aNode = aNode;
  3206. /**
  3207. * The second input.
  3208. *
  3209. * @type {Node}
  3210. */
  3211. this.bNode = bNode;
  3212. /**
  3213. * This flag can be used for type testing.
  3214. *
  3215. * @type {boolean}
  3216. * @readonly
  3217. * @default true
  3218. */
  3219. this.isOperatorNode = true;
  3220. }
  3221. /**
  3222. * This method is overwritten since the node type is inferred from the operator
  3223. * and the input node types.
  3224. *
  3225. * @param {NodeBuilder} builder - The current node builder.
  3226. * @param {string} output - The current output string.
  3227. * @return {string} The node type.
  3228. */
  3229. getNodeType( builder, output ) {
  3230. const op = this.op;
  3231. const aNode = this.aNode;
  3232. const bNode = this.bNode;
  3233. const typeA = aNode.getNodeType( builder );
  3234. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3235. if ( typeA === 'void' || typeB === 'void' ) {
  3236. return 'void';
  3237. } else if ( op === '%' ) {
  3238. return typeA;
  3239. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3240. return builder.getIntegerType( typeA );
  3241. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3242. return 'bool';
  3243. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3244. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3245. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3246. } else {
  3247. // Handle matrix operations
  3248. if ( builder.isMatrix( typeA ) ) {
  3249. if ( typeB === 'float' ) {
  3250. return typeA; // matrix * scalar = matrix
  3251. } else if ( builder.isVector( typeB ) ) {
  3252. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3253. } else if ( builder.isMatrix( typeB ) ) {
  3254. return typeA; // matrix * matrix
  3255. }
  3256. } else if ( builder.isMatrix( typeB ) ) {
  3257. if ( typeA === 'float' ) {
  3258. return typeB; // scalar * matrix = matrix
  3259. } else if ( builder.isVector( typeA ) ) {
  3260. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3261. }
  3262. }
  3263. // Handle non-matrix cases
  3264. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3265. // anytype x anytype: use the greater length vector
  3266. return typeB;
  3267. }
  3268. return typeA;
  3269. }
  3270. }
  3271. generate( builder, output ) {
  3272. const op = this.op;
  3273. const aNode = this.aNode;
  3274. const bNode = this.bNode;
  3275. const type = this.getNodeType( builder, output );
  3276. let typeA = null;
  3277. let typeB = null;
  3278. if ( type !== 'void' ) {
  3279. typeA = aNode.getNodeType( builder );
  3280. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3281. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3282. if ( builder.isVector( typeA ) ) {
  3283. typeB = typeA;
  3284. } else if ( typeA !== typeB ) {
  3285. typeA = typeB = 'float';
  3286. }
  3287. } else if ( op === '>>' || op === '<<' ) {
  3288. typeA = type;
  3289. typeB = builder.changeComponentType( typeB, 'uint' );
  3290. } else if ( builder.isMatrix( typeA ) ) {
  3291. if ( typeB === 'float' ) {
  3292. // Keep matrix type for typeA, but ensure typeB stays float
  3293. typeB = 'float';
  3294. } else if ( builder.isVector( typeB ) ) {
  3295. // matrix x vector
  3296. typeB = builder.getVectorFromMatrix( typeA );
  3297. } else if ( builder.isMatrix( typeB ) ) ; else {
  3298. typeA = typeB = type;
  3299. }
  3300. } else if ( builder.isMatrix( typeB ) ) {
  3301. if ( typeA === 'float' ) {
  3302. // Keep matrix type for typeB, but ensure typeA stays float
  3303. typeA = 'float';
  3304. } else if ( builder.isVector( typeA ) ) {
  3305. // vector x matrix
  3306. typeA = builder.getVectorFromMatrix( typeB );
  3307. } else {
  3308. typeA = typeB = type;
  3309. }
  3310. } else {
  3311. // anytype x anytype
  3312. typeA = typeB = type;
  3313. }
  3314. } else {
  3315. typeA = typeB = type;
  3316. }
  3317. const a = aNode.build( builder, typeA );
  3318. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3319. const outputLength = builder.getTypeLength( output );
  3320. const fnOpSnippet = builder.getFunctionOperator( op );
  3321. if ( output !== 'void' ) {
  3322. if ( op === '<' && outputLength > 1 ) {
  3323. if ( builder.useComparisonMethod ) {
  3324. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3325. } else {
  3326. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3327. }
  3328. } else if ( op === '<=' && outputLength > 1 ) {
  3329. if ( builder.useComparisonMethod ) {
  3330. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3331. } else {
  3332. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3333. }
  3334. } else if ( op === '>' && outputLength > 1 ) {
  3335. if ( builder.useComparisonMethod ) {
  3336. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3337. } else {
  3338. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3339. }
  3340. } else if ( op === '>=' && outputLength > 1 ) {
  3341. if ( builder.useComparisonMethod ) {
  3342. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3343. } else {
  3344. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3345. }
  3346. } else if ( op === '!' || op === '~' ) {
  3347. return builder.format( `(${op}${a})`, typeA, output );
  3348. } else if ( fnOpSnippet ) {
  3349. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3350. } else {
  3351. // Handle matrix operations
  3352. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3353. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3354. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3355. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3356. } else {
  3357. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3358. }
  3359. }
  3360. } else if ( typeA !== 'void' ) {
  3361. if ( fnOpSnippet ) {
  3362. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3363. } else {
  3364. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3365. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3366. } else {
  3367. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3368. }
  3369. }
  3370. }
  3371. }
  3372. serialize( data ) {
  3373. super.serialize( data );
  3374. data.op = this.op;
  3375. }
  3376. deserialize( data ) {
  3377. super.deserialize( data );
  3378. this.op = data.op;
  3379. }
  3380. }
  3381. /**
  3382. * Returns the addition of two or more value.
  3383. *
  3384. * @tsl
  3385. * @function
  3386. * @param {Node} aNode - The first input.
  3387. * @param {Node} bNode - The second input.
  3388. * @param {...Node} params - Additional input parameters.
  3389. * @returns {OperatorNode}
  3390. */
  3391. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3392. /**
  3393. * Returns the subtraction of two or more value.
  3394. *
  3395. * @tsl
  3396. * @function
  3397. * @param {Node} aNode - The first input.
  3398. * @param {Node} bNode - The second input.
  3399. * @param {...Node} params - Additional input parameters.
  3400. * @returns {OperatorNode}
  3401. */
  3402. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3403. /**
  3404. * Returns the multiplication of two or more value.
  3405. *
  3406. * @tsl
  3407. * @function
  3408. * @param {Node} aNode - The first input.
  3409. * @param {Node} bNode - The second input.
  3410. * @param {...Node} params - Additional input parameters.
  3411. * @returns {OperatorNode}
  3412. */
  3413. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3414. /**
  3415. * Returns the division of two or more value.
  3416. *
  3417. * @tsl
  3418. * @function
  3419. * @param {Node} aNode - The first input.
  3420. * @param {Node} bNode - The second input.
  3421. * @param {...Node} params - Additional input parameters.
  3422. * @returns {OperatorNode}
  3423. */
  3424. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3425. /**
  3426. * Computes the remainder of dividing the first node by the second, for integer values.
  3427. *
  3428. * @tsl
  3429. * @function
  3430. * @param {Node} aNode - The first input.
  3431. * @param {Node} bNode - The second input.
  3432. * @returns {OperatorNode}
  3433. */
  3434. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3435. /**
  3436. * Checks if two nodes are equal.
  3437. *
  3438. * @tsl
  3439. * @function
  3440. * @param {Node} aNode - The first input.
  3441. * @param {Node} bNode - The second input.
  3442. * @returns {OperatorNode}
  3443. */
  3444. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3445. /**
  3446. * Checks if two nodes are not equal.
  3447. *
  3448. * @tsl
  3449. * @function
  3450. * @param {Node} aNode - The first input.
  3451. * @param {Node} bNode - The second input.
  3452. * @returns {OperatorNode}
  3453. */
  3454. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3455. /**
  3456. * Checks if the first node is less than the second.
  3457. *
  3458. * @tsl
  3459. * @function
  3460. * @param {Node} aNode - The first input.
  3461. * @param {Node} bNode - The second input.
  3462. * @returns {OperatorNode}
  3463. */
  3464. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3465. /**
  3466. * Checks if the first node is greater than the second.
  3467. *
  3468. * @tsl
  3469. * @function
  3470. * @param {Node} aNode - The first input.
  3471. * @param {Node} bNode - The second input.
  3472. * @returns {OperatorNode}
  3473. */
  3474. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3475. /**
  3476. * Checks if the first node is less than or equal to the second.
  3477. *
  3478. * @tsl
  3479. * @function
  3480. * @param {Node} aNode - The first input.
  3481. * @param {Node} bNode - The second input.
  3482. * @returns {OperatorNode}
  3483. */
  3484. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3485. /**
  3486. * Checks if the first node is greater than or equal to the second.
  3487. *
  3488. * @tsl
  3489. * @function
  3490. * @param {Node} aNode - The first input.
  3491. * @param {Node} bNode - The second input.
  3492. * @returns {OperatorNode}
  3493. */
  3494. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3495. /**
  3496. * Performs logical AND on two nodes.
  3497. *
  3498. * @tsl
  3499. * @function
  3500. * @param {Node} aNode - The first input.
  3501. * @param {Node} bNode - The second input.
  3502. * @returns {OperatorNode}
  3503. */
  3504. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3505. /**
  3506. * Performs logical OR on two nodes.
  3507. *
  3508. * @tsl
  3509. * @function
  3510. * @param {Node} aNode - The first input.
  3511. * @param {Node} bNode - The second input.
  3512. * @returns {OperatorNode}
  3513. */
  3514. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3515. /**
  3516. * Performs logical NOT on a node.
  3517. *
  3518. * @tsl
  3519. * @function
  3520. * @param {Node} aNode - The first input.
  3521. * @param {Node} bNode - The second input.
  3522. * @returns {OperatorNode}
  3523. */
  3524. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3525. /**
  3526. * Performs logical XOR on two nodes.
  3527. *
  3528. * @tsl
  3529. * @function
  3530. * @param {Node} aNode - The first input.
  3531. * @param {Node} bNode - The second input.
  3532. * @returns {OperatorNode}
  3533. */
  3534. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3535. /**
  3536. * Performs bitwise AND on two nodes.
  3537. *
  3538. * @tsl
  3539. * @function
  3540. * @param {Node} aNode - The first input.
  3541. * @param {Node} bNode - The second input.
  3542. * @returns {OperatorNode}
  3543. */
  3544. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3545. /**
  3546. * Performs bitwise NOT on a node.
  3547. *
  3548. * @tsl
  3549. * @function
  3550. * @param {Node} aNode - The first input.
  3551. * @param {Node} bNode - The second input.
  3552. * @returns {OperatorNode}
  3553. */
  3554. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3555. /**
  3556. * Performs bitwise OR on two nodes.
  3557. *
  3558. * @tsl
  3559. * @function
  3560. * @param {Node} aNode - The first input.
  3561. * @param {Node} bNode - The second input.
  3562. * @returns {OperatorNode}
  3563. */
  3564. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3565. /**
  3566. * Performs bitwise XOR on two nodes.
  3567. *
  3568. * @tsl
  3569. * @function
  3570. * @param {Node} aNode - The first input.
  3571. * @param {Node} bNode - The second input.
  3572. * @returns {OperatorNode}
  3573. */
  3574. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3575. /**
  3576. * Shifts a node to the left.
  3577. *
  3578. * @tsl
  3579. * @function
  3580. * @param {Node} aNode - The node to shift.
  3581. * @param {Node} bNode - The value to shift.
  3582. * @returns {OperatorNode}
  3583. */
  3584. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3585. /**
  3586. * Shifts a node to the right.
  3587. *
  3588. * @tsl
  3589. * @function
  3590. * @param {Node} aNode - The node to shift.
  3591. * @param {Node} bNode - The value to shift.
  3592. * @returns {OperatorNode}
  3593. */
  3594. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3595. addMethodChaining( 'add', add );
  3596. addMethodChaining( 'sub', sub );
  3597. addMethodChaining( 'mul', mul );
  3598. addMethodChaining( 'div', div );
  3599. addMethodChaining( 'modInt', modInt );
  3600. addMethodChaining( 'equal', equal );
  3601. addMethodChaining( 'notEqual', notEqual );
  3602. addMethodChaining( 'lessThan', lessThan );
  3603. addMethodChaining( 'greaterThan', greaterThan );
  3604. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3605. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3606. addMethodChaining( 'and', and );
  3607. addMethodChaining( 'or', or );
  3608. addMethodChaining( 'not', not );
  3609. addMethodChaining( 'xor', xor );
  3610. addMethodChaining( 'bitAnd', bitAnd );
  3611. addMethodChaining( 'bitNot', bitNot );
  3612. addMethodChaining( 'bitOr', bitOr );
  3613. addMethodChaining( 'bitXor', bitXor );
  3614. addMethodChaining( 'shiftLeft', shiftLeft );
  3615. addMethodChaining( 'shiftRight', shiftRight );
  3616. /**
  3617. * @tsl
  3618. * @function
  3619. * @deprecated since r168. Use {@link modInt} instead.
  3620. *
  3621. * @param {...any} params
  3622. * @returns {Function}
  3623. */
  3624. const remainder = ( ...params ) => { // @deprecated, r168
  3625. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3626. return modInt( ...params );
  3627. };
  3628. addMethodChaining( 'remainder', remainder );
  3629. /**
  3630. * This node represents a variety of mathematical methods available in shaders.
  3631. * They are divided into three categories:
  3632. *
  3633. * - Methods with one input like `sin`, `cos` or `normalize`.
  3634. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3635. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3636. *
  3637. * @augments TempNode
  3638. */
  3639. class MathNode extends TempNode {
  3640. static get type() {
  3641. return 'MathNode';
  3642. }
  3643. /**
  3644. * Constructs a new math node.
  3645. *
  3646. * @param {string} method - The method name.
  3647. * @param {Node} aNode - The first input.
  3648. * @param {?Node} [bNode=null] - The second input.
  3649. * @param {?Node} [cNode=null] - The third input.
  3650. */
  3651. constructor( method, aNode, bNode = null, cNode = null ) {
  3652. super();
  3653. /**
  3654. * The method name.
  3655. *
  3656. * @type {string}
  3657. */
  3658. this.method = method;
  3659. /**
  3660. * The first input.
  3661. *
  3662. * @type {Node}
  3663. */
  3664. this.aNode = aNode;
  3665. /**
  3666. * The second input.
  3667. *
  3668. * @type {?Node}
  3669. * @default null
  3670. */
  3671. this.bNode = bNode;
  3672. /**
  3673. * The third input.
  3674. *
  3675. * @type {?Node}
  3676. * @default null
  3677. */
  3678. this.cNode = cNode;
  3679. /**
  3680. * This flag can be used for type testing.
  3681. *
  3682. * @type {boolean}
  3683. * @readonly
  3684. * @default true
  3685. */
  3686. this.isMathNode = true;
  3687. }
  3688. /**
  3689. * The input type is inferred from the node types of the input nodes.
  3690. *
  3691. * @param {NodeBuilder} builder - The current node builder.
  3692. * @return {string} The input type.
  3693. */
  3694. getInputType( builder ) {
  3695. const aType = this.aNode.getNodeType( builder );
  3696. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3697. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3698. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3699. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3700. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3701. if ( aLen > bLen && aLen > cLen ) {
  3702. return aType;
  3703. } else if ( bLen > cLen ) {
  3704. return bType;
  3705. } else if ( cLen > aLen ) {
  3706. return cType;
  3707. }
  3708. return aType;
  3709. }
  3710. /**
  3711. * The selected method as well as the input type determine the node type of this node.
  3712. *
  3713. * @param {NodeBuilder} builder - The current node builder.
  3714. * @return {string} The node type.
  3715. */
  3716. getNodeType( builder ) {
  3717. const method = this.method;
  3718. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3719. return 'float';
  3720. } else if ( method === MathNode.CROSS ) {
  3721. return 'vec3';
  3722. } else if ( method === MathNode.ALL ) {
  3723. return 'bool';
  3724. } else if ( method === MathNode.EQUALS ) {
  3725. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3726. } else if ( method === MathNode.MOD ) {
  3727. return this.aNode.getNodeType( builder );
  3728. } else {
  3729. return this.getInputType( builder );
  3730. }
  3731. }
  3732. generate( builder, output ) {
  3733. let method = this.method;
  3734. const type = this.getNodeType( builder );
  3735. const inputType = this.getInputType( builder );
  3736. const a = this.aNode;
  3737. const b = this.bNode;
  3738. const c = this.cNode;
  3739. const coordinateSystem = builder.renderer.coordinateSystem;
  3740. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3741. // dir can be either a direction vector or a normal vector
  3742. // upper-left 3x3 of matrix is assumed to be orthogonal
  3743. let tA = a;
  3744. let tB = b;
  3745. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3746. tB = vec4( vec3( tB ), 0.0 );
  3747. } else {
  3748. tA = vec4( vec3( tA ), 0.0 );
  3749. }
  3750. const mulNode = mul( tA, tB ).xyz;
  3751. return normalize( mulNode ).build( builder, output );
  3752. } else if ( method === MathNode.NEGATE ) {
  3753. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3754. } else if ( method === MathNode.ONE_MINUS ) {
  3755. return sub( 1.0, a ).build( builder, output );
  3756. } else if ( method === MathNode.RECIPROCAL ) {
  3757. return div( 1.0, a ).build( builder, output );
  3758. } else if ( method === MathNode.DIFFERENCE ) {
  3759. return abs( sub( a, b ) ).build( builder, output );
  3760. } else {
  3761. const params = [];
  3762. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3763. params.push(
  3764. a.build( builder, type ),
  3765. b.build( builder, type )
  3766. );
  3767. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3768. params.push(
  3769. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3770. b.build( builder, inputType )
  3771. );
  3772. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3773. params.push(
  3774. a.build( builder, inputType ),
  3775. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3776. );
  3777. } else if ( method === MathNode.REFRACT ) {
  3778. params.push(
  3779. a.build( builder, inputType ),
  3780. b.build( builder, inputType ),
  3781. c.build( builder, 'float' )
  3782. );
  3783. } else if ( method === MathNode.MIX ) {
  3784. params.push(
  3785. a.build( builder, inputType ),
  3786. b.build( builder, inputType ),
  3787. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3788. );
  3789. } else {
  3790. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3791. method = 'atan2';
  3792. }
  3793. params.push( a.build( builder, inputType ) );
  3794. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3795. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3796. }
  3797. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3798. }
  3799. }
  3800. serialize( data ) {
  3801. super.serialize( data );
  3802. data.method = this.method;
  3803. }
  3804. deserialize( data ) {
  3805. super.deserialize( data );
  3806. this.method = data.method;
  3807. }
  3808. }
  3809. // 1 input
  3810. MathNode.ALL = 'all';
  3811. MathNode.ANY = 'any';
  3812. MathNode.RADIANS = 'radians';
  3813. MathNode.DEGREES = 'degrees';
  3814. MathNode.EXP = 'exp';
  3815. MathNode.EXP2 = 'exp2';
  3816. MathNode.LOG = 'log';
  3817. MathNode.LOG2 = 'log2';
  3818. MathNode.SQRT = 'sqrt';
  3819. MathNode.INVERSE_SQRT = 'inversesqrt';
  3820. MathNode.FLOOR = 'floor';
  3821. MathNode.CEIL = 'ceil';
  3822. MathNode.NORMALIZE = 'normalize';
  3823. MathNode.FRACT = 'fract';
  3824. MathNode.SIN = 'sin';
  3825. MathNode.COS = 'cos';
  3826. MathNode.TAN = 'tan';
  3827. MathNode.ASIN = 'asin';
  3828. MathNode.ACOS = 'acos';
  3829. MathNode.ATAN = 'atan';
  3830. MathNode.ABS = 'abs';
  3831. MathNode.SIGN = 'sign';
  3832. MathNode.LENGTH = 'length';
  3833. MathNode.NEGATE = 'negate';
  3834. MathNode.ONE_MINUS = 'oneMinus';
  3835. MathNode.DFDX = 'dFdx';
  3836. MathNode.DFDY = 'dFdy';
  3837. MathNode.ROUND = 'round';
  3838. MathNode.RECIPROCAL = 'reciprocal';
  3839. MathNode.TRUNC = 'trunc';
  3840. MathNode.FWIDTH = 'fwidth';
  3841. MathNode.TRANSPOSE = 'transpose';
  3842. // 2 inputs
  3843. MathNode.BITCAST = 'bitcast';
  3844. MathNode.EQUALS = 'equals';
  3845. MathNode.MIN = 'min';
  3846. MathNode.MAX = 'max';
  3847. MathNode.MOD = 'mod';
  3848. MathNode.STEP = 'step';
  3849. MathNode.REFLECT = 'reflect';
  3850. MathNode.DISTANCE = 'distance';
  3851. MathNode.DIFFERENCE = 'difference';
  3852. MathNode.DOT = 'dot';
  3853. MathNode.CROSS = 'cross';
  3854. MathNode.POW = 'pow';
  3855. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3856. // 3 inputs
  3857. MathNode.MIX = 'mix';
  3858. MathNode.CLAMP = 'clamp';
  3859. MathNode.REFRACT = 'refract';
  3860. MathNode.SMOOTHSTEP = 'smoothstep';
  3861. MathNode.FACEFORWARD = 'faceforward';
  3862. // 1 inputs
  3863. /**
  3864. * A small value used to handle floating-point precision errors.
  3865. *
  3866. * @tsl
  3867. * @type {Node<float>}
  3868. */
  3869. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3870. /**
  3871. * Represents infinity.
  3872. *
  3873. * @tsl
  3874. * @type {Node<float>}
  3875. */
  3876. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3877. /**
  3878. * Represents PI.
  3879. *
  3880. * @tsl
  3881. * @type {Node<float>}
  3882. */
  3883. const PI = /*@__PURE__*/ float( Math.PI );
  3884. /**
  3885. * Represents PI * 2.
  3886. *
  3887. * @tsl
  3888. * @type {Node<float>}
  3889. */
  3890. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3891. /**
  3892. * Returns `true` if all components of `x` are `true`.
  3893. *
  3894. * @tsl
  3895. * @function
  3896. * @param {Node | number} x - The parameter.
  3897. * @returns {Node<bool>}
  3898. */
  3899. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3900. /**
  3901. * Returns `true` if any components of `x` are `true`.
  3902. *
  3903. * @tsl
  3904. * @function
  3905. * @param {Node | number} x - The parameter.
  3906. * @returns {Node<bool>}
  3907. */
  3908. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3909. /**
  3910. * Converts a quantity in degrees to radians.
  3911. *
  3912. * @tsl
  3913. * @function
  3914. * @param {Node | number} x - The input in degrees.
  3915. * @returns {Node}
  3916. */
  3917. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3918. /**
  3919. * Convert a quantity in radians to degrees.
  3920. *
  3921. * @tsl
  3922. * @function
  3923. * @param {Node | number} x - The input in radians.
  3924. * @returns {Node}
  3925. */
  3926. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3927. /**
  3928. * Returns the natural exponentiation of the parameter.
  3929. *
  3930. * @tsl
  3931. * @function
  3932. * @param {Node | number} x - The parameter.
  3933. * @returns {Node}
  3934. */
  3935. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3936. /**
  3937. * Returns 2 raised to the power of the parameter.
  3938. *
  3939. * @tsl
  3940. * @function
  3941. * @param {Node | number} x - The parameter.
  3942. * @returns {Node}
  3943. */
  3944. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3945. /**
  3946. * Returns the natural logarithm of the parameter.
  3947. *
  3948. * @tsl
  3949. * @function
  3950. * @param {Node | number} x - The parameter.
  3951. * @returns {Node}
  3952. */
  3953. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3954. /**
  3955. * Returns the base 2 logarithm of the parameter.
  3956. *
  3957. * @tsl
  3958. * @function
  3959. * @param {Node | number} x - The parameter.
  3960. * @returns {Node}
  3961. */
  3962. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3963. /**
  3964. * Returns the square root of the parameter.
  3965. *
  3966. * @tsl
  3967. * @function
  3968. * @param {Node | number} x - The parameter.
  3969. * @returns {Node}
  3970. */
  3971. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3972. /**
  3973. * Returns the inverse of the square root of the parameter.
  3974. *
  3975. * @tsl
  3976. * @function
  3977. * @param {Node | number} x - The parameter.
  3978. * @returns {Node}
  3979. */
  3980. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3981. /**
  3982. * Finds the nearest integer less than or equal to the parameter.
  3983. *
  3984. * @tsl
  3985. * @function
  3986. * @param {Node | number} x - The parameter.
  3987. * @returns {Node}
  3988. */
  3989. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3990. /**
  3991. * Finds the nearest integer that is greater than or equal to the parameter.
  3992. *
  3993. * @tsl
  3994. * @function
  3995. * @param {Node | number} x - The parameter.
  3996. * @returns {Node}
  3997. */
  3998. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3999. /**
  4000. * Calculates the unit vector in the same direction as the original vector.
  4001. *
  4002. * @tsl
  4003. * @function
  4004. * @param {Node} x - The input vector.
  4005. * @returns {Node}
  4006. */
  4007. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  4008. /**
  4009. * Computes the fractional part of the parameter.
  4010. *
  4011. * @tsl
  4012. * @function
  4013. * @param {Node | number} x - The parameter.
  4014. * @returns {Node}
  4015. */
  4016. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  4017. /**
  4018. * Returns the sine of the parameter.
  4019. *
  4020. * @tsl
  4021. * @function
  4022. * @param {Node | number} x - The parameter.
  4023. * @returns {Node}
  4024. */
  4025. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  4026. /**
  4027. * Returns the cosine of the parameter.
  4028. *
  4029. * @tsl
  4030. * @function
  4031. * @param {Node | number} x - The parameter.
  4032. * @returns {Node}
  4033. */
  4034. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  4035. /**
  4036. * Returns the tangent of the parameter.
  4037. *
  4038. * @tsl
  4039. * @function
  4040. * @param {Node | number} x - The parameter.
  4041. * @returns {Node}
  4042. */
  4043. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  4044. /**
  4045. * Returns the arcsine of the parameter.
  4046. *
  4047. * @tsl
  4048. * @function
  4049. * @param {Node | number} x - The parameter.
  4050. * @returns {Node}
  4051. */
  4052. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  4053. /**
  4054. * Returns the arccosine of the parameter.
  4055. *
  4056. * @tsl
  4057. * @function
  4058. * @param {Node | number} x - The parameter.
  4059. * @returns {Node}
  4060. */
  4061. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  4062. /**
  4063. * Returns the arc-tangent of the parameter.
  4064. * If two parameters are provided, the result is `atan2(y/x)`.
  4065. *
  4066. * @tsl
  4067. * @function
  4068. * @param {Node | number} y - The y parameter.
  4069. * @param {?(Node | number)} x - The x parameter.
  4070. * @returns {Node}
  4071. */
  4072. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  4073. /**
  4074. * Returns the absolute value of the parameter.
  4075. *
  4076. * @tsl
  4077. * @function
  4078. * @param {Node | number} x - The parameter.
  4079. * @returns {Node}
  4080. */
  4081. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  4082. /**
  4083. * Extracts the sign of the parameter.
  4084. *
  4085. * @tsl
  4086. * @function
  4087. * @param {Node | number} x - The parameter.
  4088. * @returns {Node}
  4089. */
  4090. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  4091. /**
  4092. * Calculates the length of a vector.
  4093. *
  4094. * @tsl
  4095. * @function
  4096. * @param {Node} x - The parameter.
  4097. * @returns {Node<float>}
  4098. */
  4099. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  4100. /**
  4101. * Negates the value of the parameter (-x).
  4102. *
  4103. * @tsl
  4104. * @function
  4105. * @param {Node | number} x - The parameter.
  4106. * @returns {Node}
  4107. */
  4108. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  4109. /**
  4110. * Return `1` minus the parameter.
  4111. *
  4112. * @tsl
  4113. * @function
  4114. * @param {Node | number} x - The parameter.
  4115. * @returns {Node}
  4116. */
  4117. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  4118. /**
  4119. * Returns the partial derivative of the parameter with respect to x.
  4120. *
  4121. * @tsl
  4122. * @function
  4123. * @param {Node | number} x - The parameter.
  4124. * @returns {Node}
  4125. */
  4126. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  4127. /**
  4128. * Returns the partial derivative of the parameter with respect to y.
  4129. *
  4130. * @tsl
  4131. * @function
  4132. * @param {Node | number} x - The parameter.
  4133. * @returns {Node}
  4134. */
  4135. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  4136. /**
  4137. * Rounds the parameter to the nearest integer.
  4138. *
  4139. * @tsl
  4140. * @function
  4141. * @param {Node | number} x - The parameter.
  4142. * @returns {Node}
  4143. */
  4144. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  4145. /**
  4146. * Returns the reciprocal of the parameter `(1/x)`.
  4147. *
  4148. * @tsl
  4149. * @function
  4150. * @param {Node | number} x - The parameter.
  4151. * @returns {Node}
  4152. */
  4153. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  4154. /**
  4155. * Truncates the parameter, removing the fractional part.
  4156. *
  4157. * @tsl
  4158. * @function
  4159. * @param {Node | number} x - The parameter.
  4160. * @returns {Node}
  4161. */
  4162. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  4163. /**
  4164. * Returns the sum of the absolute derivatives in x and y.
  4165. *
  4166. * @tsl
  4167. * @function
  4168. * @param {Node | number} x - The parameter.
  4169. * @returns {Node}
  4170. */
  4171. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  4172. /**
  4173. * Returns the transpose of a matrix.
  4174. *
  4175. * @tsl
  4176. * @function
  4177. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4178. * @returns {Node}
  4179. */
  4180. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  4181. // 2 inputs
  4182. /**
  4183. * Reinterpret the bit representation of a value in one type as a value in another type.
  4184. *
  4185. * @tsl
  4186. * @function
  4187. * @param {Node | number} x - The parameter.
  4188. * @param {string} y - The new type.
  4189. * @returns {Node}
  4190. */
  4191. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  4192. /**
  4193. * Returns `true` if `x` equals `y`.
  4194. *
  4195. * @tsl
  4196. * @function
  4197. * @param {Node | number} x - The first parameter.
  4198. * @param {Node | number} y - The second parameter.
  4199. * @returns {Node<bool>}
  4200. */
  4201. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  4202. /**
  4203. * Returns the lesser of two values.
  4204. *
  4205. * @tsl
  4206. * @function
  4207. * @param {Node | number} x - The y parameter.
  4208. * @param {Node | number} y - The x parameter.
  4209. * @returns {Node}
  4210. */
  4211. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  4212. /**
  4213. * Returns the greater of two values.
  4214. *
  4215. * @tsl
  4216. * @function
  4217. * @param {Node | number} x - The y parameter.
  4218. * @param {Node | number} y - The x parameter.
  4219. * @returns {Node}
  4220. */
  4221. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  4222. /**
  4223. * Computes the remainder of dividing the first node by the second one.
  4224. *
  4225. * @tsl
  4226. * @function
  4227. * @param {Node | number} x - The y parameter.
  4228. * @param {Node | number} y - The x parameter.
  4229. * @returns {Node}
  4230. */
  4231. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  4232. /**
  4233. * Generate a step function by comparing two values.
  4234. *
  4235. * @tsl
  4236. * @function
  4237. * @param {Node | number} x - The y parameter.
  4238. * @param {Node | number} y - The x parameter.
  4239. * @returns {Node}
  4240. */
  4241. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  4242. /**
  4243. * Calculates the reflection direction for an incident vector.
  4244. *
  4245. * @tsl
  4246. * @function
  4247. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4248. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4249. * @returns {Node<vec2|vec3|vec4>}
  4250. */
  4251. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  4252. /**
  4253. * Calculates the distance between two points.
  4254. *
  4255. * @tsl
  4256. * @function
  4257. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4258. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4259. * @returns {Node<float>}
  4260. */
  4261. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  4262. /**
  4263. * Calculates the absolute difference between two values.
  4264. *
  4265. * @tsl
  4266. * @function
  4267. * @param {Node | number} x - The first parameter.
  4268. * @param {Node | number} y - The second parameter.
  4269. * @returns {Node}
  4270. */
  4271. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  4272. /**
  4273. * Calculates the dot product of two vectors.
  4274. *
  4275. * @tsl
  4276. * @function
  4277. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4278. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4279. * @returns {Node<float>}
  4280. */
  4281. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  4282. /**
  4283. * Calculates the cross product of two vectors.
  4284. *
  4285. * @tsl
  4286. * @function
  4287. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4288. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4289. * @returns {Node<vec2|vec3|vec4>}
  4290. */
  4291. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  4292. /**
  4293. * Return the value of the first parameter raised to the power of the second one.
  4294. *
  4295. * @tsl
  4296. * @function
  4297. * @param {Node | number} x - The first parameter.
  4298. * @param {Node | number} y - The second parameter.
  4299. * @returns {Node}
  4300. */
  4301. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  4302. /**
  4303. * Returns the square of the parameter.
  4304. *
  4305. * @tsl
  4306. * @function
  4307. * @param {Node | number} x - The first parameter.
  4308. * @returns {Node}
  4309. */
  4310. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4311. /**
  4312. * Returns the cube of the parameter.
  4313. *
  4314. * @tsl
  4315. * @function
  4316. * @param {Node | number} x - The first parameter.
  4317. * @returns {Node}
  4318. */
  4319. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4320. /**
  4321. * Returns the fourth power of the parameter.
  4322. *
  4323. * @tsl
  4324. * @function
  4325. * @param {Node | number} x - The first parameter.
  4326. * @returns {Node}
  4327. */
  4328. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4329. /**
  4330. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4331. *
  4332. * @tsl
  4333. * @function
  4334. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4335. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4336. * @returns {Node}
  4337. */
  4338. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4339. /**
  4340. * Returns the cube root of a number.
  4341. *
  4342. * @tsl
  4343. * @function
  4344. * @param {Node | number} a - The first parameter.
  4345. * @returns {Node}
  4346. */
  4347. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4348. /**
  4349. * Calculate the squared length of a vector.
  4350. *
  4351. * @tsl
  4352. * @function
  4353. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4354. * @returns {Node<float>}
  4355. */
  4356. const lengthSq = ( a ) => dot( a, a );
  4357. /**
  4358. * Linearly interpolates between two values.
  4359. *
  4360. * @tsl
  4361. * @function
  4362. * @param {Node | number} a - The first parameter.
  4363. * @param {Node | number} b - The second parameter.
  4364. * @param {Node | number} t - The interpolation value.
  4365. * @returns {Node}
  4366. */
  4367. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4368. /**
  4369. * Constrains a value to lie between two further values.
  4370. *
  4371. * @tsl
  4372. * @function
  4373. * @param {Node | number} value - The value to constrain.
  4374. * @param {Node | number} [low=0] - The lower bound.
  4375. * @param {Node | number} [high=1] - The upper bound.
  4376. * @returns {Node}
  4377. */
  4378. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4379. /**
  4380. * Constrains a value between `0` and `1`.
  4381. *
  4382. * @tsl
  4383. * @function
  4384. * @param {Node | number} value - The value to constrain.
  4385. * @returns {Node}
  4386. */
  4387. const saturate = ( value ) => clamp( value );
  4388. /**
  4389. * Calculates the refraction direction for an incident vector.
  4390. *
  4391. * @tsl
  4392. * @function
  4393. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4394. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4395. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4396. * @returns {Node<vec2|vec3|vec4>}
  4397. */
  4398. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4399. /**
  4400. * Performs a Hermite interpolation between two values.
  4401. *
  4402. * @tsl
  4403. * @function
  4404. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4405. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4406. * @param {Node | number} x - The source value for interpolation.
  4407. * @returns {Node}
  4408. */
  4409. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4410. /**
  4411. * Returns a vector pointing in the same direction as another.
  4412. *
  4413. * @tsl
  4414. * @function
  4415. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4416. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4417. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4418. * @returns {Node<vec2|vec3|vec4>}
  4419. */
  4420. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4421. /**
  4422. * Returns a random value for the given uv.
  4423. *
  4424. * @tsl
  4425. * @function
  4426. * @param {Node<vec2>} uv - The uv node.
  4427. * @returns {Node<float>}
  4428. */
  4429. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4430. const a = 12.9898, b = 78.233, c = 43758.5453;
  4431. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4432. return fract( sin( sn ).mul( c ) );
  4433. } );
  4434. /**
  4435. * Alias for `mix()` with a different parameter order.
  4436. *
  4437. * @tsl
  4438. * @function
  4439. * @param {Node | number} t - The interpolation value.
  4440. * @param {Node | number} e1 - The first parameter.
  4441. * @param {Node | number} e2 - The second parameter.
  4442. * @returns {Node}
  4443. */
  4444. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4445. /**
  4446. * Alias for `smoothstep()` with a different parameter order.
  4447. *
  4448. * @tsl
  4449. * @function
  4450. * @param {Node | number} x - The source value for interpolation.
  4451. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4452. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4453. * @returns {Node}
  4454. */
  4455. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4456. /**
  4457. * Returns the arc-tangent of the quotient of its parameters.
  4458. *
  4459. * @tsl
  4460. * @function
  4461. * @deprecated since r172. Use {@link atan} instead.
  4462. *
  4463. * @param {Node | number} y - The y parameter.
  4464. * @param {Node | number} x - The x parameter.
  4465. * @returns {Node}
  4466. */
  4467. const atan2 = ( y, x ) => { // @deprecated, r172
  4468. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4469. return atan( y, x );
  4470. };
  4471. // GLSL alias function
  4472. const faceforward = faceForward;
  4473. const inversesqrt = inverseSqrt;
  4474. // Method chaining
  4475. addMethodChaining( 'all', all );
  4476. addMethodChaining( 'any', any );
  4477. addMethodChaining( 'equals', equals );
  4478. addMethodChaining( 'radians', radians );
  4479. addMethodChaining( 'degrees', degrees );
  4480. addMethodChaining( 'exp', exp );
  4481. addMethodChaining( 'exp2', exp2 );
  4482. addMethodChaining( 'log', log );
  4483. addMethodChaining( 'log2', log2 );
  4484. addMethodChaining( 'sqrt', sqrt );
  4485. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4486. addMethodChaining( 'floor', floor );
  4487. addMethodChaining( 'ceil', ceil );
  4488. addMethodChaining( 'normalize', normalize );
  4489. addMethodChaining( 'fract', fract );
  4490. addMethodChaining( 'sin', sin );
  4491. addMethodChaining( 'cos', cos );
  4492. addMethodChaining( 'tan', tan );
  4493. addMethodChaining( 'asin', asin );
  4494. addMethodChaining( 'acos', acos );
  4495. addMethodChaining( 'atan', atan );
  4496. addMethodChaining( 'abs', abs );
  4497. addMethodChaining( 'sign', sign );
  4498. addMethodChaining( 'length', length );
  4499. addMethodChaining( 'lengthSq', lengthSq );
  4500. addMethodChaining( 'negate', negate );
  4501. addMethodChaining( 'oneMinus', oneMinus );
  4502. addMethodChaining( 'dFdx', dFdx );
  4503. addMethodChaining( 'dFdy', dFdy );
  4504. addMethodChaining( 'round', round );
  4505. addMethodChaining( 'reciprocal', reciprocal );
  4506. addMethodChaining( 'trunc', trunc );
  4507. addMethodChaining( 'fwidth', fwidth );
  4508. addMethodChaining( 'atan2', atan2 );
  4509. addMethodChaining( 'min', min$1 );
  4510. addMethodChaining( 'max', max$1 );
  4511. addMethodChaining( 'mod', mod );
  4512. addMethodChaining( 'step', step );
  4513. addMethodChaining( 'reflect', reflect );
  4514. addMethodChaining( 'distance', distance );
  4515. addMethodChaining( 'dot', dot );
  4516. addMethodChaining( 'cross', cross );
  4517. addMethodChaining( 'pow', pow );
  4518. addMethodChaining( 'pow2', pow2 );
  4519. addMethodChaining( 'pow3', pow3 );
  4520. addMethodChaining( 'pow4', pow4 );
  4521. addMethodChaining( 'transformDirection', transformDirection );
  4522. addMethodChaining( 'mix', mixElement );
  4523. addMethodChaining( 'clamp', clamp );
  4524. addMethodChaining( 'refract', refract );
  4525. addMethodChaining( 'smoothstep', smoothstepElement );
  4526. addMethodChaining( 'faceForward', faceForward );
  4527. addMethodChaining( 'difference', difference );
  4528. addMethodChaining( 'saturate', saturate );
  4529. addMethodChaining( 'cbrt', cbrt );
  4530. addMethodChaining( 'transpose', transpose );
  4531. addMethodChaining( 'rand', rand );
  4532. /**
  4533. * Represents a logical `if/else` statement. Can be used as an alternative
  4534. * to the `If()`/`Else()` syntax.
  4535. *
  4536. * The corresponding TSL `select()` looks like so:
  4537. * ```js
  4538. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4539. * ```
  4540. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4541. * determine the outcome of the entire statement.
  4542. *
  4543. * @augments Node
  4544. */
  4545. class ConditionalNode extends Node {
  4546. static get type() {
  4547. return 'ConditionalNode';
  4548. }
  4549. /**
  4550. * Constructs a new conditional node.
  4551. *
  4552. * @param {Node} condNode - The node that defines the condition.
  4553. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4554. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4555. */
  4556. constructor( condNode, ifNode, elseNode = null ) {
  4557. super();
  4558. /**
  4559. * The node that defines the condition.
  4560. *
  4561. * @type {Node}
  4562. */
  4563. this.condNode = condNode;
  4564. /**
  4565. * The node that is evaluate when the condition ends up `true`.
  4566. *
  4567. * @type {Node}
  4568. */
  4569. this.ifNode = ifNode;
  4570. /**
  4571. * The node that is evaluate when the condition ends up `false`.
  4572. *
  4573. * @type {?Node}
  4574. * @default null
  4575. */
  4576. this.elseNode = elseNode;
  4577. }
  4578. /**
  4579. * This method is overwritten since the node type is inferred from the if/else
  4580. * nodes.
  4581. *
  4582. * @param {NodeBuilder} builder - The current node builder.
  4583. * @return {string} The node type.
  4584. */
  4585. getNodeType( builder ) {
  4586. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4587. if ( ifNode === undefined ) {
  4588. // fallback setup
  4589. this.setup( builder );
  4590. return this.getNodeType( builder );
  4591. }
  4592. const ifType = ifNode.getNodeType( builder );
  4593. if ( elseNode !== null ) {
  4594. const elseType = elseNode.getNodeType( builder );
  4595. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4596. return elseType;
  4597. }
  4598. }
  4599. return ifType;
  4600. }
  4601. setup( builder ) {
  4602. const condNode = this.condNode.cache();
  4603. const ifNode = this.ifNode.cache();
  4604. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4605. //
  4606. const currentNodeBlock = builder.context.nodeBlock;
  4607. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4608. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4609. //
  4610. const properties = builder.getNodeProperties( this );
  4611. properties.condNode = condNode;
  4612. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4613. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4614. }
  4615. generate( builder, output ) {
  4616. const type = this.getNodeType( builder );
  4617. const nodeData = builder.getDataFromNode( this );
  4618. if ( nodeData.nodeProperty !== undefined ) {
  4619. return nodeData.nodeProperty;
  4620. }
  4621. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4622. const needsOutput = output !== 'void';
  4623. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4624. nodeData.nodeProperty = nodeProperty;
  4625. const nodeSnippet = condNode.build( builder, 'bool' );
  4626. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4627. let ifSnippet = ifNode.build( builder, type );
  4628. if ( ifSnippet ) {
  4629. if ( needsOutput ) {
  4630. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4631. } else {
  4632. ifSnippet = 'return ' + ifSnippet + ';';
  4633. }
  4634. }
  4635. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4636. if ( elseNode !== null ) {
  4637. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4638. let elseSnippet = elseNode.build( builder, type );
  4639. if ( elseSnippet ) {
  4640. if ( needsOutput ) {
  4641. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4642. } else {
  4643. elseSnippet = 'return ' + elseSnippet + ';';
  4644. }
  4645. }
  4646. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4647. } else {
  4648. builder.addFlowCode( '\n\n' );
  4649. }
  4650. return builder.format( nodeProperty, type, output );
  4651. }
  4652. }
  4653. /**
  4654. * TSL function for creating a conditional node.
  4655. *
  4656. * @tsl
  4657. * @function
  4658. * @param {Node} condNode - The node that defines the condition.
  4659. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4660. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4661. * @returns {ConditionalNode}
  4662. */
  4663. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4664. addMethodChaining( 'select', select );
  4665. // Deprecated
  4666. /**
  4667. * @tsl
  4668. * @function
  4669. * @deprecated since r168. Use {@link select} instead.
  4670. *
  4671. * @param {...any} params
  4672. * @returns {ConditionalNode}
  4673. */
  4674. const cond = ( ...params ) => { // @deprecated, r168
  4675. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4676. return select( ...params );
  4677. };
  4678. addMethodChaining( 'cond', cond );
  4679. /**
  4680. * This node can be used as a context management component for another node.
  4681. * {@link NodeBuilder} performs its node building process in a specific context and
  4682. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4683. *
  4684. * ```js
  4685. *node.context( { getUV: () => customCoord } );
  4686. *```
  4687. * @augments Node
  4688. */
  4689. class ContextNode extends Node {
  4690. static get type() {
  4691. return 'ContextNode';
  4692. }
  4693. /**
  4694. * Constructs a new context node.
  4695. *
  4696. * @param {Node} node - The node whose context should be modified.
  4697. * @param {Object} [value={}] - The modified context data.
  4698. */
  4699. constructor( node, value = {} ) {
  4700. super();
  4701. /**
  4702. * This flag can be used for type testing.
  4703. *
  4704. * @type {boolean}
  4705. * @readonly
  4706. * @default true
  4707. */
  4708. this.isContextNode = true;
  4709. /**
  4710. * The node whose context should be modified.
  4711. *
  4712. * @type {Node}
  4713. */
  4714. this.node = node;
  4715. /**
  4716. * The modified context data.
  4717. *
  4718. * @type {Object}
  4719. * @default {}
  4720. */
  4721. this.value = value;
  4722. }
  4723. /**
  4724. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  4725. *
  4726. * @return {Node} A reference to {@link ContextNode#node}.
  4727. */
  4728. getScope() {
  4729. return this.node.getScope();
  4730. }
  4731. /**
  4732. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  4733. *
  4734. * @param {NodeBuilder} builder - The current node builder.
  4735. * @return {string} The node type.
  4736. */
  4737. getNodeType( builder ) {
  4738. return this.node.getNodeType( builder );
  4739. }
  4740. analyze( builder ) {
  4741. this.node.build( builder );
  4742. }
  4743. setup( builder ) {
  4744. const previousContext = builder.getContext();
  4745. builder.setContext( { ...builder.context, ...this.value } );
  4746. const node = this.node.build( builder );
  4747. builder.setContext( previousContext );
  4748. return node;
  4749. }
  4750. generate( builder, output ) {
  4751. const previousContext = builder.getContext();
  4752. builder.setContext( { ...builder.context, ...this.value } );
  4753. const snippet = this.node.build( builder, output );
  4754. builder.setContext( previousContext );
  4755. return snippet;
  4756. }
  4757. }
  4758. /**
  4759. * TSL function for creating a context node.
  4760. *
  4761. * @tsl
  4762. * @function
  4763. * @param {Node} node - The node whose context should be modified.
  4764. * @param {Object} [value={}] - The modified context data.
  4765. * @returns {ContextNode}
  4766. */
  4767. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4768. /**
  4769. * TSL function for defining a label context value for a given node.
  4770. *
  4771. * @tsl
  4772. * @function
  4773. * @param {Node} node - The node whose context should be modified.
  4774. * @param {string} name - The name/label to set.
  4775. * @returns {ContextNode}
  4776. */
  4777. const label = ( node, name ) => context( node, { label: name } );
  4778. addMethodChaining( 'context', context );
  4779. addMethodChaining( 'label', label );
  4780. /**
  4781. * Class for representing shader variables as nodes. Variables are created from
  4782. * existing nodes like the following:
  4783. *
  4784. * ```js
  4785. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4786. * ```
  4787. *
  4788. * @augments Node
  4789. */
  4790. class VarNode extends Node {
  4791. static get type() {
  4792. return 'VarNode';
  4793. }
  4794. /**
  4795. * Constructs a new variable node.
  4796. *
  4797. * @param {Node} node - The node for which a variable should be created.
  4798. * @param {?string} [name=null] - The name of the variable in the shader.
  4799. * @param {boolean} [readOnly=false] - The read-only flag.
  4800. */
  4801. constructor( node, name = null, readOnly = false ) {
  4802. super();
  4803. /**
  4804. * The node for which a variable should be created.
  4805. *
  4806. * @type {Node}
  4807. */
  4808. this.node = node;
  4809. /**
  4810. * The name of the variable in the shader. If no name is defined,
  4811. * the node system auto-generates one.
  4812. *
  4813. * @type {?string}
  4814. * @default null
  4815. */
  4816. this.name = name;
  4817. /**
  4818. * `VarNode` sets this property to `true` by default.
  4819. *
  4820. * @type {boolean}
  4821. * @default true
  4822. */
  4823. this.global = true;
  4824. /**
  4825. * This flag can be used for type testing.
  4826. *
  4827. * @type {boolean}
  4828. * @readonly
  4829. * @default true
  4830. */
  4831. this.isVarNode = true;
  4832. /**
  4833. *
  4834. * The read-only flag.
  4835. *
  4836. * @type {boolean}
  4837. * @default false
  4838. */
  4839. this.readOnly = readOnly;
  4840. }
  4841. getHash( builder ) {
  4842. return this.name || super.getHash( builder );
  4843. }
  4844. getMemberType( builder, name ) {
  4845. return this.node.getMemberType( builder, name );
  4846. }
  4847. getElementType( builder ) {
  4848. return this.node.getElementType( builder );
  4849. }
  4850. getNodeType( builder ) {
  4851. return this.node.getNodeType( builder );
  4852. }
  4853. generate( builder ) {
  4854. const { node, name, readOnly } = this;
  4855. const { renderer } = builder;
  4856. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4857. let isDeterministic = false;
  4858. let shouldTreatAsReadOnly = false;
  4859. if ( readOnly ) {
  4860. isDeterministic = builder.isDeterministic( node );
  4861. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4862. }
  4863. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4864. const snippet = node.build( builder, vectorType );
  4865. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4866. const propertyName = builder.getPropertyName( nodeVar );
  4867. let declarationPrefix = propertyName;
  4868. if ( shouldTreatAsReadOnly ) {
  4869. if ( isWebGPUBackend ) {
  4870. declarationPrefix = isDeterministic
  4871. ? `const ${ propertyName }`
  4872. : `let ${ propertyName }`;
  4873. } else {
  4874. const count = builder.getArrayCount( node );
  4875. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  4876. }
  4877. }
  4878. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4879. return propertyName;
  4880. }
  4881. }
  4882. /**
  4883. * TSL function for creating a var node.
  4884. *
  4885. * @tsl
  4886. * @function
  4887. * @param {Node} node - The node for which a variable should be created.
  4888. * @param {?string} name - The name of the variable in the shader.
  4889. * @returns {VarNode}
  4890. */
  4891. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4892. /**
  4893. * TSL function for creating a var node.
  4894. *
  4895. * @tsl
  4896. * @function
  4897. * @param {Node} node - The node for which a variable should be created.
  4898. * @param {?string} name - The name of the variable in the shader.
  4899. * @returns {VarNode}
  4900. */
  4901. const Var = ( node, name = null ) => createVar( node, name ).append();
  4902. /**
  4903. * TSL function for creating a const node.
  4904. *
  4905. * @tsl
  4906. * @function
  4907. * @param {Node} node - The node for which a constant should be created.
  4908. * @param {?string} name - The name of the constant in the shader.
  4909. * @returns {VarNode}
  4910. */
  4911. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4912. // Method chaining
  4913. addMethodChaining( 'toVar', Var );
  4914. addMethodChaining( 'toConst', Const );
  4915. // Deprecated
  4916. /**
  4917. * @tsl
  4918. * @function
  4919. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4920. *
  4921. * @param {any} node
  4922. * @returns {VarNode}
  4923. */
  4924. const temp = ( node ) => { // @deprecated, r170
  4925. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4926. return createVar( node );
  4927. };
  4928. addMethodChaining( 'temp', temp );
  4929. /**
  4930. * Class for representing shader varyings as nodes. Varyings are create from
  4931. * existing nodes like the following:
  4932. *
  4933. * ```js
  4934. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  4935. * ```
  4936. *
  4937. * @augments Node
  4938. */
  4939. class VaryingNode extends Node {
  4940. static get type() {
  4941. return 'VaryingNode';
  4942. }
  4943. /**
  4944. * Constructs a new varying node.
  4945. *
  4946. * @param {Node} node - The node for which a varying should be created.
  4947. * @param {?string} name - The name of the varying in the shader.
  4948. */
  4949. constructor( node, name = null ) {
  4950. super();
  4951. /**
  4952. * The node for which a varying should be created.
  4953. *
  4954. * @type {Node}
  4955. */
  4956. this.node = node;
  4957. /**
  4958. * The name of the varying in the shader. If no name is defined,
  4959. * the node system auto-generates one.
  4960. *
  4961. * @type {?string}
  4962. * @default null
  4963. */
  4964. this.name = name;
  4965. /**
  4966. * This flag can be used for type testing.
  4967. *
  4968. * @type {boolean}
  4969. * @readonly
  4970. * @default true
  4971. */
  4972. this.isVaryingNode = true;
  4973. }
  4974. /**
  4975. * The method is overwritten so it always returns `true`.
  4976. *
  4977. * @param {NodeBuilder} builder - The current node builder.
  4978. * @return {boolean} Whether this node is global or not.
  4979. */
  4980. isGlobal( /*builder*/ ) {
  4981. return true;
  4982. }
  4983. getHash( builder ) {
  4984. return this.name || super.getHash( builder );
  4985. }
  4986. getNodeType( builder ) {
  4987. // VaryingNode is auto type
  4988. return this.node.getNodeType( builder );
  4989. }
  4990. /**
  4991. * This method performs the setup of a varying node with the current node builder.
  4992. *
  4993. * @param {NodeBuilder} builder - The current node builder.
  4994. * @return {NodeVarying} The node varying from the node builder.
  4995. */
  4996. setupVarying( builder ) {
  4997. const properties = builder.getNodeProperties( this );
  4998. let varying = properties.varying;
  4999. if ( varying === undefined ) {
  5000. const name = this.name;
  5001. const type = this.getNodeType( builder );
  5002. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  5003. properties.node = this.node;
  5004. }
  5005. // this property can be used to check if the varying can be optimized for a variable
  5006. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5007. return varying;
  5008. }
  5009. setup( builder ) {
  5010. this.setupVarying( builder );
  5011. }
  5012. analyze( builder ) {
  5013. this.setupVarying( builder );
  5014. return this.node.analyze( builder );
  5015. }
  5016. generate( builder ) {
  5017. const properties = builder.getNodeProperties( this );
  5018. const varying = this.setupVarying( builder );
  5019. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  5020. if ( properties.propertyName === undefined || needsReassign ) {
  5021. const type = this.getNodeType( builder );
  5022. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5023. // force node run in vertex stage
  5024. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  5025. properties.propertyName = propertyName;
  5026. if ( needsReassign ) {
  5027. // once reassign varying in fragment stage
  5028. properties.reassignPosition = false;
  5029. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  5030. properties.reassignPosition = true;
  5031. }
  5032. }
  5033. return builder.getPropertyName( varying );
  5034. }
  5035. }
  5036. /**
  5037. * TSL function for creating a varying node.
  5038. *
  5039. * @tsl
  5040. * @function
  5041. * @param {Node} node - The node for which a varying should be created.
  5042. * @param {?string} name - The name of the varying in the shader.
  5043. * @returns {VaryingNode}
  5044. */
  5045. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  5046. /**
  5047. * Computes a node in the vertex stage.
  5048. *
  5049. * @tsl
  5050. * @function
  5051. * @param {Node} node - The node which should be executed in the vertex stage.
  5052. * @returns {VaryingNode}
  5053. */
  5054. const vertexStage = ( node ) => varying( node );
  5055. addMethodChaining( 'toVarying', varying );
  5056. addMethodChaining( 'toVertexStage', vertexStage );
  5057. // Deprecated
  5058. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5059. console.warn( 'TSL.VaryingNode: .varying() has been renamed to .toVarying().' );
  5060. return varying( ...params );
  5061. } );
  5062. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5063. console.warn( 'TSL.VaryingNode: .vertexStage() has been renamed to .toVertexStage().' );
  5064. return varying( ...params );
  5065. } );
  5066. /**
  5067. * Converts the given color value from sRGB to linear-sRGB color space.
  5068. *
  5069. * @tsl
  5070. * @function
  5071. * @param {Node<vec3>} color - The sRGB color.
  5072. * @return {Node<vec3>} The linear-sRGB color.
  5073. */
  5074. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5075. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5076. const b = color.mul( 0.0773993808 );
  5077. const factor = color.lessThanEqual( 0.04045 );
  5078. const rgbResult = mix( a, b, factor );
  5079. return rgbResult;
  5080. } ).setLayout( {
  5081. name: 'sRGBTransferEOTF',
  5082. type: 'vec3',
  5083. inputs: [
  5084. { name: 'color', type: 'vec3' }
  5085. ]
  5086. } );
  5087. /**
  5088. * Converts the given color value from linear-sRGB to sRGB color space.
  5089. *
  5090. * @tsl
  5091. * @function
  5092. * @param {Node<vec3>} color - The linear-sRGB color.
  5093. * @return {Node<vec3>} The sRGB color.
  5094. */
  5095. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5096. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5097. const b = color.mul( 12.92 );
  5098. const factor = color.lessThanEqual( 0.0031308 );
  5099. const rgbResult = mix( a, b, factor );
  5100. return rgbResult;
  5101. } ).setLayout( {
  5102. name: 'sRGBTransferOETF',
  5103. type: 'vec3',
  5104. inputs: [
  5105. { name: 'color', type: 'vec3' }
  5106. ]
  5107. } );
  5108. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5109. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5110. /**
  5111. * This node represents a color space conversion. Meaning it converts
  5112. * a color value from a source to a target color space.
  5113. *
  5114. * @augments TempNode
  5115. */
  5116. class ColorSpaceNode extends TempNode {
  5117. static get type() {
  5118. return 'ColorSpaceNode';
  5119. }
  5120. /**
  5121. * Constructs a new color space node.
  5122. *
  5123. * @param {Node} colorNode - Represents the color to convert.
  5124. * @param {string} source - The source color space.
  5125. * @param {string} target - The target color space.
  5126. */
  5127. constructor( colorNode, source, target ) {
  5128. super( 'vec4' );
  5129. /**
  5130. * Represents the color to convert.
  5131. *
  5132. * @type {Node}
  5133. */
  5134. this.colorNode = colorNode;
  5135. /**
  5136. * The source color space.
  5137. *
  5138. * @type {string}
  5139. */
  5140. this.source = source;
  5141. /**
  5142. * The target color space.
  5143. *
  5144. * @type {string}
  5145. */
  5146. this.target = target;
  5147. }
  5148. /**
  5149. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5150. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5151. * color management and renderer.
  5152. *
  5153. * @param {NodeBuilder} builder - The current node builder.
  5154. * @param {string} colorSpace - The color space to resolve.
  5155. * @return {string} The resolved color space.
  5156. */
  5157. resolveColorSpace( builder, colorSpace ) {
  5158. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5159. return ColorManagement.workingColorSpace;
  5160. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5161. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5162. }
  5163. return colorSpace;
  5164. }
  5165. setup( builder ) {
  5166. const { colorNode } = this;
  5167. const source = this.resolveColorSpace( builder, this.source );
  5168. const target = this.resolveColorSpace( builder, this.target );
  5169. let outputNode = colorNode;
  5170. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5171. return outputNode;
  5172. }
  5173. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5174. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5175. }
  5176. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5177. outputNode = vec4(
  5178. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5179. outputNode.a
  5180. );
  5181. }
  5182. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5183. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5184. }
  5185. return outputNode;
  5186. }
  5187. }
  5188. /**
  5189. * TSL function for converting a given color node to the current output color space.
  5190. *
  5191. * @tsl
  5192. * @function
  5193. * @param {Node} node - Represents the node to convert.
  5194. * @returns {ColorSpaceNode}
  5195. */
  5196. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  5197. /**
  5198. * TSL function for converting a given color node to the current working color space.
  5199. *
  5200. * @tsl
  5201. * @function
  5202. * @param {Node} node - Represents the node to convert.
  5203. * @returns {ColorSpaceNode}
  5204. */
  5205. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  5206. /**
  5207. * TSL function for converting a given color node from the current working color space to the given color space.
  5208. *
  5209. * @tsl
  5210. * @function
  5211. * @param {Node} node - Represents the node to convert.
  5212. * @param {string} colorSpace - The target color space.
  5213. * @returns {ColorSpaceNode}
  5214. */
  5215. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  5216. /**
  5217. * TSL function for converting a given color node from the given color space to the current working color space.
  5218. *
  5219. * @tsl
  5220. * @function
  5221. * @param {Node} node - Represents the node to convert.
  5222. * @param {string} colorSpace - The source color space.
  5223. * @returns {ColorSpaceNode}
  5224. */
  5225. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  5226. /**
  5227. * TSL function for converting a given color node from one color space to another one.
  5228. *
  5229. * @tsl
  5230. * @function
  5231. * @param {Node} node - Represents the node to convert.
  5232. * @param {string} sourceColorSpace - The source color space.
  5233. * @param {string} targetColorSpace - The target color space.
  5234. * @returns {ColorSpaceNode}
  5235. */
  5236. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5237. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  5238. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  5239. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5240. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5241. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5242. /**
  5243. * This class is only relevant if the referenced property is array-like.
  5244. * In this case, `ReferenceElementNode` allows to refer to a specific
  5245. * element inside the data structure via an index.
  5246. *
  5247. * @augments ArrayElementNode
  5248. */
  5249. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5250. static get type() {
  5251. return 'ReferenceElementNode';
  5252. }
  5253. /**
  5254. * Constructs a new reference element node.
  5255. *
  5256. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5257. * @param {Node} indexNode - The index node that defines the element access.
  5258. */
  5259. constructor( referenceNode, indexNode ) {
  5260. super( referenceNode, indexNode );
  5261. /**
  5262. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5263. * property references to the current node.
  5264. *
  5265. * @type {?ReferenceBaseNode}
  5266. * @default null
  5267. */
  5268. this.referenceNode = referenceNode;
  5269. /**
  5270. * This flag can be used for type testing.
  5271. *
  5272. * @type {boolean}
  5273. * @readonly
  5274. * @default true
  5275. */
  5276. this.isReferenceElementNode = true;
  5277. }
  5278. /**
  5279. * This method is overwritten since the node type is inferred from
  5280. * the uniform type of the reference node.
  5281. *
  5282. * @return {string} The node type.
  5283. */
  5284. getNodeType() {
  5285. return this.referenceNode.uniformType;
  5286. }
  5287. generate( builder ) {
  5288. const snippet = super.generate( builder );
  5289. const arrayType = this.referenceNode.getNodeType();
  5290. const elementType = this.getNodeType();
  5291. return builder.format( snippet, arrayType, elementType );
  5292. }
  5293. };
  5294. /**
  5295. * Base class for nodes which establishes a reference to a property of another object.
  5296. * In this way, the value of the node is automatically linked to the value of
  5297. * referenced object. Reference nodes internally represent the linked value
  5298. * as a uniform.
  5299. *
  5300. * @augments Node
  5301. */
  5302. class ReferenceBaseNode extends Node {
  5303. static get type() {
  5304. return 'ReferenceBaseNode';
  5305. }
  5306. /**
  5307. * Constructs a new reference base node.
  5308. *
  5309. * @param {string} property - The name of the property the node refers to.
  5310. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5311. * @param {?Object} [object=null] - The object the property belongs to.
  5312. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5313. */
  5314. constructor( property, uniformType, object = null, count = null ) {
  5315. super();
  5316. /**
  5317. * The name of the property the node refers to.
  5318. *
  5319. * @type {string}
  5320. */
  5321. this.property = property;
  5322. /**
  5323. * The uniform type that should be used to represent the property value.
  5324. *
  5325. * @type {string}
  5326. */
  5327. this.uniformType = uniformType;
  5328. /**
  5329. * The object the property belongs to.
  5330. *
  5331. * @type {?Object}
  5332. * @default null
  5333. */
  5334. this.object = object;
  5335. /**
  5336. * When the linked property is an array, this parameter defines its length.
  5337. *
  5338. * @type {?number}
  5339. * @default null
  5340. */
  5341. this.count = count;
  5342. /**
  5343. * The property name might have dots so nested properties can be referred.
  5344. * The hierarchy of the names is stored inside this array.
  5345. *
  5346. * @type {Array<string>}
  5347. */
  5348. this.properties = property.split( '.' );
  5349. /**
  5350. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5351. * since the final reference might be updated from calling code.
  5352. *
  5353. * @type {?Object}
  5354. * @default null
  5355. */
  5356. this.reference = object;
  5357. /**
  5358. * The uniform node that holds the value of the reference node.
  5359. *
  5360. * @type {UniformNode}
  5361. * @default null
  5362. */
  5363. this.node = null;
  5364. /**
  5365. * The uniform group of the internal uniform.
  5366. *
  5367. * @type {UniformGroupNode}
  5368. * @default null
  5369. */
  5370. this.group = null;
  5371. /**
  5372. * Overwritten since reference nodes are updated per object.
  5373. *
  5374. * @type {string}
  5375. * @default 'object'
  5376. */
  5377. this.updateType = NodeUpdateType.OBJECT;
  5378. }
  5379. /**
  5380. * Sets the uniform group for this reference node.
  5381. *
  5382. * @param {UniformGroupNode} group - The uniform group to set.
  5383. * @return {ReferenceBaseNode} A reference to this node.
  5384. */
  5385. setGroup( group ) {
  5386. this.group = group;
  5387. return this;
  5388. }
  5389. /**
  5390. * When the referred property is array-like, this method can be used
  5391. * to access elements via an index node.
  5392. *
  5393. * @param {IndexNode} indexNode - indexNode.
  5394. * @return {ReferenceElementNode} A reference to an element.
  5395. */
  5396. element( indexNode ) {
  5397. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5398. }
  5399. /**
  5400. * Sets the node type which automatically defines the internal
  5401. * uniform type.
  5402. *
  5403. * @param {string} uniformType - The type to set.
  5404. */
  5405. setNodeType( uniformType ) {
  5406. const node = uniform( null, uniformType ).getSelf();
  5407. if ( this.group !== null ) {
  5408. node.setGroup( this.group );
  5409. }
  5410. this.node = node;
  5411. }
  5412. /**
  5413. * This method is overwritten since the node type is inferred from
  5414. * the type of the reference node.
  5415. *
  5416. * @param {NodeBuilder} builder - The current node builder.
  5417. * @return {string} The node type.
  5418. */
  5419. getNodeType( builder ) {
  5420. if ( this.node === null ) {
  5421. this.updateReference( builder );
  5422. this.updateValue();
  5423. }
  5424. return this.node.getNodeType( builder );
  5425. }
  5426. /**
  5427. * Returns the property value from the given referred object.
  5428. *
  5429. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5430. * @return {any} The value.
  5431. */
  5432. getValueFromReference( object = this.reference ) {
  5433. const { properties } = this;
  5434. let value = object[ properties[ 0 ] ];
  5435. for ( let i = 1; i < properties.length; i ++ ) {
  5436. value = value[ properties[ i ] ];
  5437. }
  5438. return value;
  5439. }
  5440. /**
  5441. * Allows to update the reference based on the given state. The state is only
  5442. * evaluated {@link ReferenceBaseNode#object} is not set.
  5443. *
  5444. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5445. * @return {Object} The updated reference.
  5446. */
  5447. updateReference( state ) {
  5448. this.reference = this.object !== null ? this.object : state.object;
  5449. return this.reference;
  5450. }
  5451. /**
  5452. * The output of the reference node is the internal uniform node.
  5453. *
  5454. * @return {UniformNode} The output node.
  5455. */
  5456. setup() {
  5457. this.updateValue();
  5458. return this.node;
  5459. }
  5460. /**
  5461. * Overwritten to to update the internal uniform value.
  5462. *
  5463. * @param {NodeFrame} frame - A reference to the current node frame.
  5464. */
  5465. update( /*frame*/ ) {
  5466. this.updateValue();
  5467. }
  5468. /**
  5469. * Retrieves the value from the referred object property and uses it
  5470. * to updated the internal uniform.
  5471. */
  5472. updateValue() {
  5473. if ( this.node === null ) this.setNodeType( this.uniformType );
  5474. const value = this.getValueFromReference();
  5475. if ( Array.isArray( value ) ) {
  5476. this.node.array = value;
  5477. } else {
  5478. this.node.value = value;
  5479. }
  5480. }
  5481. }
  5482. /**
  5483. * TSL function for creating a reference base node.
  5484. *
  5485. * @tsl
  5486. * @function
  5487. * @param {string} name - The name of the property the node refers to.
  5488. * @param {string} type - The uniform type that should be used to represent the property value.
  5489. * @param {Object} object - The object the property belongs to.
  5490. * @returns {ReferenceBaseNode}
  5491. */
  5492. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5493. /**
  5494. * This node is a special type of reference node which is intended
  5495. * for linking renderer properties with node values.
  5496. * ```js
  5497. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5498. * ```
  5499. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5500. * automatically be updated.
  5501. *
  5502. * @augments ReferenceBaseNode
  5503. */
  5504. class RendererReferenceNode extends ReferenceBaseNode {
  5505. static get type() {
  5506. return 'RendererReferenceNode';
  5507. }
  5508. /**
  5509. * Constructs a new renderer reference node.
  5510. *
  5511. * @param {string} property - The name of the property the node refers to.
  5512. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5513. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5514. * the node refers to the renderer of the current state.
  5515. */
  5516. constructor( property, inputType, renderer = null ) {
  5517. super( property, inputType, renderer );
  5518. /**
  5519. * The renderer the property belongs to. When no renderer is set,
  5520. * the node refers to the renderer of the current state.
  5521. *
  5522. * @type {?Renderer}
  5523. * @default null
  5524. */
  5525. this.renderer = renderer;
  5526. this.setGroup( renderGroup );
  5527. }
  5528. /**
  5529. * Updates the reference based on the given state. The state is only evaluated
  5530. * {@link RendererReferenceNode#renderer} is not set.
  5531. *
  5532. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5533. * @return {Object} The updated reference.
  5534. */
  5535. updateReference( state ) {
  5536. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5537. return this.reference;
  5538. }
  5539. }
  5540. /**
  5541. * TSL function for creating a renderer reference node.
  5542. *
  5543. * @tsl
  5544. * @function
  5545. * @param {string} name - The name of the property the node refers to.
  5546. * @param {string} type - The uniform type that should be used to represent the property value.
  5547. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5548. * the node refers to the renderer of the current state.
  5549. * @returns {RendererReferenceNode}
  5550. */
  5551. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5552. /**
  5553. * This node represents a tone mapping operation.
  5554. *
  5555. * @augments TempNode
  5556. */
  5557. class ToneMappingNode extends TempNode {
  5558. static get type() {
  5559. return 'ToneMappingNode';
  5560. }
  5561. /**
  5562. * Constructs a new tone mapping node.
  5563. *
  5564. * @param {number} toneMapping - The tone mapping type.
  5565. * @param {Node} exposureNode - The tone mapping exposure.
  5566. * @param {Node} [colorNode=null] - The color node to process.
  5567. */
  5568. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5569. super( 'vec3' );
  5570. /**
  5571. * The tone mapping type.
  5572. *
  5573. * @type {number}
  5574. */
  5575. this.toneMapping = toneMapping;
  5576. /**
  5577. * The tone mapping exposure.
  5578. *
  5579. * @type {Node}
  5580. * @default null
  5581. */
  5582. this.exposureNode = exposureNode;
  5583. /**
  5584. * Represents the color to process.
  5585. *
  5586. * @type {?Node}
  5587. * @default null
  5588. */
  5589. this.colorNode = colorNode;
  5590. }
  5591. /**
  5592. * Overwrites the default `customCacheKey()` implementation by including the tone
  5593. * mapping type into the cache key.
  5594. *
  5595. * @return {number} The hash.
  5596. */
  5597. customCacheKey() {
  5598. return hash$1( this.toneMapping );
  5599. }
  5600. setup( builder ) {
  5601. const colorNode = this.colorNode || builder.context.color;
  5602. const toneMapping = this.toneMapping;
  5603. if ( toneMapping === NoToneMapping ) return colorNode;
  5604. let outputNode = null;
  5605. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5606. if ( toneMappingFn !== null ) {
  5607. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5608. } else {
  5609. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5610. outputNode = colorNode;
  5611. }
  5612. return outputNode;
  5613. }
  5614. }
  5615. /**
  5616. * TSL function for creating a tone mapping node.
  5617. *
  5618. * @tsl
  5619. * @function
  5620. * @param {number} mapping - The tone mapping type.
  5621. * @param {Node<float> | number} exposure - The tone mapping exposure.
  5622. * @param {Node<vec3> | Color} color - The color node to process.
  5623. * @returns {ToneMappingNode<vec3>}
  5624. */
  5625. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5626. /**
  5627. * TSL object that represents the global tone mapping exposure of the renderer.
  5628. *
  5629. * @tsl
  5630. * @type {RendererReferenceNode<vec3>}
  5631. */
  5632. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5633. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5634. /**
  5635. * In earlier `three.js` versions it was only possible to define attribute data
  5636. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5637. * on the node level.
  5638. * ```js
  5639. * const geometry = new THREE.PlaneGeometry();
  5640. * const positionAttribute = geometry.getAttribute( 'position' );
  5641. *
  5642. * const colors = [];
  5643. * for ( let i = 0; i < position.count; i ++ ) {
  5644. * colors.push( 1, 0, 0 );
  5645. * }
  5646. *
  5647. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5648. * ```
  5649. * This new approach is especially interesting when geometry data are generated via
  5650. * compute shaders. The below line converts a storage buffer into an attribute node.
  5651. * ```js
  5652. * material.positionNode = positionBuffer.toAttribute();
  5653. * ```
  5654. * @augments InputNode
  5655. */
  5656. class BufferAttributeNode extends InputNode {
  5657. static get type() {
  5658. return 'BufferAttributeNode';
  5659. }
  5660. /**
  5661. * Constructs a new buffer attribute node.
  5662. *
  5663. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5664. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5665. * @param {number} [bufferStride=0] - The buffer stride.
  5666. * @param {number} [bufferOffset=0] - The buffer offset.
  5667. */
  5668. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5669. super( value, bufferType );
  5670. /**
  5671. * This flag can be used for type testing.
  5672. *
  5673. * @type {boolean}
  5674. * @readonly
  5675. * @default true
  5676. */
  5677. this.isBufferNode = true;
  5678. /**
  5679. * The buffer type (e.g. `'vec3'`).
  5680. *
  5681. * @type {?string}
  5682. * @default null
  5683. */
  5684. this.bufferType = bufferType;
  5685. /**
  5686. * The buffer stride.
  5687. *
  5688. * @type {number}
  5689. * @default 0
  5690. */
  5691. this.bufferStride = bufferStride;
  5692. /**
  5693. * The buffer offset.
  5694. *
  5695. * @type {number}
  5696. * @default 0
  5697. */
  5698. this.bufferOffset = bufferOffset;
  5699. /**
  5700. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5701. * if you are planning to update the attribute data per frame.
  5702. *
  5703. * @type {number}
  5704. * @default StaticDrawUsage
  5705. */
  5706. this.usage = StaticDrawUsage;
  5707. /**
  5708. * Whether the attribute is instanced or not.
  5709. *
  5710. * @type {boolean}
  5711. * @default false
  5712. */
  5713. this.instanced = false;
  5714. /**
  5715. * A reference to the buffer attribute.
  5716. *
  5717. * @type {?BufferAttribute}
  5718. * @default null
  5719. */
  5720. this.attribute = null;
  5721. /**
  5722. * `BufferAttributeNode` sets this property to `true` by default.
  5723. *
  5724. * @type {boolean}
  5725. * @default true
  5726. */
  5727. this.global = true;
  5728. if ( value && value.isBufferAttribute === true ) {
  5729. this.attribute = value;
  5730. this.usage = value.usage;
  5731. this.instanced = value.isInstancedBufferAttribute;
  5732. }
  5733. }
  5734. /**
  5735. * This method is overwritten since the attribute data might be shared
  5736. * and thus the hash should be shared as well.
  5737. *
  5738. * @param {NodeBuilder} builder - The current node builder.
  5739. * @return {string} The hash.
  5740. */
  5741. getHash( builder ) {
  5742. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5743. let bufferData = builder.globalCache.getData( this.value );
  5744. if ( bufferData === undefined ) {
  5745. bufferData = {
  5746. node: this
  5747. };
  5748. builder.globalCache.setData( this.value, bufferData );
  5749. }
  5750. return bufferData.node.uuid;
  5751. }
  5752. return this.uuid;
  5753. }
  5754. /**
  5755. * This method is overwritten since the node type is inferred from
  5756. * the buffer attribute.
  5757. *
  5758. * @param {NodeBuilder} builder - The current node builder.
  5759. * @return {string} The node type.
  5760. */
  5761. getNodeType( builder ) {
  5762. if ( this.bufferType === null ) {
  5763. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5764. }
  5765. return this.bufferType;
  5766. }
  5767. /**
  5768. * Depending on which value was passed to the node, `setup()` behaves
  5769. * differently. If no instance of `BufferAttribute` was passed, the method
  5770. * creates an internal attribute and configures it respectively.
  5771. *
  5772. * @param {NodeBuilder} builder - The current node builder.
  5773. */
  5774. setup( builder ) {
  5775. if ( this.attribute !== null ) return;
  5776. const type = this.getNodeType( builder );
  5777. const array = this.value;
  5778. const itemSize = builder.getTypeLength( type );
  5779. const stride = this.bufferStride || itemSize;
  5780. const offset = this.bufferOffset;
  5781. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5782. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5783. buffer.setUsage( this.usage );
  5784. this.attribute = bufferAttribute;
  5785. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5786. }
  5787. /**
  5788. * Generates the code snippet of the buffer attribute node.
  5789. *
  5790. * @param {NodeBuilder} builder - The current node builder.
  5791. * @return {string} The generated code snippet.
  5792. */
  5793. generate( builder ) {
  5794. const nodeType = this.getNodeType( builder );
  5795. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5796. const propertyName = builder.getPropertyName( nodeAttribute );
  5797. let output = null;
  5798. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5799. this.name = propertyName;
  5800. output = propertyName;
  5801. } else {
  5802. const nodeVarying = varying( this );
  5803. output = nodeVarying.build( builder, nodeType );
  5804. }
  5805. return output;
  5806. }
  5807. /**
  5808. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5809. *
  5810. * @param {NodeBuilder} builder - The current node builder.
  5811. * @return {string} The input type.
  5812. */
  5813. getInputType( /*builder*/ ) {
  5814. return 'bufferAttribute';
  5815. }
  5816. /**
  5817. * Sets the `usage` property to the given value.
  5818. *
  5819. * @param {number} value - The usage to set.
  5820. * @return {BufferAttributeNode} A reference to this node.
  5821. */
  5822. setUsage( value ) {
  5823. this.usage = value;
  5824. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5825. this.attribute.usage = value;
  5826. }
  5827. return this;
  5828. }
  5829. /**
  5830. * Sets the `instanced` property to the given value.
  5831. *
  5832. * @param {boolean} value - The value to set.
  5833. * @return {BufferAttributeNode} A reference to this node.
  5834. */
  5835. setInstanced( value ) {
  5836. this.instanced = value;
  5837. return this;
  5838. }
  5839. }
  5840. /**
  5841. * TSL function for creating a buffer attribute node.
  5842. *
  5843. * @tsl
  5844. * @function
  5845. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5846. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5847. * @param {number} [stride=0] - The buffer stride.
  5848. * @param {number} [offset=0] - The buffer offset.
  5849. * @returns {BufferAttributeNode}
  5850. */
  5851. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5852. /**
  5853. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5854. * Use this function if attribute data are updated per frame.
  5855. *
  5856. * @tsl
  5857. * @function
  5858. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5859. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5860. * @param {number} [stride=0] - The buffer stride.
  5861. * @param {number} [offset=0] - The buffer offset.
  5862. * @returns {BufferAttributeNode}
  5863. */
  5864. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5865. /**
  5866. * TSL function for creating a buffer attribute node but with enabled instancing
  5867. *
  5868. * @tsl
  5869. * @function
  5870. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5871. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5872. * @param {number} [stride=0] - The buffer stride.
  5873. * @param {number} [offset=0] - The buffer offset.
  5874. * @returns {BufferAttributeNode}
  5875. */
  5876. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5877. /**
  5878. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5879. *
  5880. * @tsl
  5881. * @function
  5882. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5883. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  5884. * @param {number} [stride=0] - The buffer stride.
  5885. * @param {number} [offset=0] - The buffer offset.
  5886. * @returns {BufferAttributeNode}
  5887. */
  5888. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5889. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5890. /**
  5891. * TODO
  5892. *
  5893. * @augments Node
  5894. */
  5895. class ComputeNode extends Node {
  5896. static get type() {
  5897. return 'ComputeNode';
  5898. }
  5899. /**
  5900. * Constructs a new compute node.
  5901. *
  5902. * @param {Node} computeNode - TODO
  5903. * @param {number} count - TODO.
  5904. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  5905. */
  5906. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5907. super( 'void' );
  5908. /**
  5909. * This flag can be used for type testing.
  5910. *
  5911. * @type {boolean}
  5912. * @readonly
  5913. * @default true
  5914. */
  5915. this.isComputeNode = true;
  5916. /**
  5917. * TODO
  5918. *
  5919. * @type {Node}
  5920. */
  5921. this.computeNode = computeNode;
  5922. /**
  5923. * TODO
  5924. *
  5925. * @type {number}
  5926. */
  5927. this.count = count;
  5928. /**
  5929. * TODO
  5930. *
  5931. * @type {Array<number>}
  5932. * @default [64]
  5933. */
  5934. this.workgroupSize = workgroupSize;
  5935. /**
  5936. * TODO
  5937. *
  5938. * @type {number}
  5939. */
  5940. this.dispatchCount = 0;
  5941. /**
  5942. * TODO
  5943. *
  5944. * @type {number}
  5945. */
  5946. this.version = 1;
  5947. /**
  5948. * The name or label of the uniform.
  5949. *
  5950. * @type {string}
  5951. * @default ''
  5952. */
  5953. this.name = '';
  5954. /**
  5955. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5956. * is executed once per object by default.
  5957. *
  5958. * @type {string}
  5959. * @default 'object'
  5960. */
  5961. this.updateBeforeType = NodeUpdateType.OBJECT;
  5962. /**
  5963. * TODO
  5964. *
  5965. * @type {?Function}
  5966. */
  5967. this.onInitFunction = null;
  5968. this.updateDispatchCount();
  5969. }
  5970. /**
  5971. * Executes the `dispose` event for this node.
  5972. */
  5973. dispose() {
  5974. this.dispatchEvent( { type: 'dispose' } );
  5975. }
  5976. /**
  5977. * Sets the {@link ComputeNode#name} property.
  5978. *
  5979. * @param {string} name - The name of the uniform.
  5980. * @return {ComputeNode} A reference to this node.
  5981. */
  5982. label( name ) {
  5983. this.name = name;
  5984. return this;
  5985. }
  5986. /**
  5987. * TODO
  5988. */
  5989. updateDispatchCount() {
  5990. const { count, workgroupSize } = this;
  5991. let size = workgroupSize[ 0 ];
  5992. for ( let i = 1; i < workgroupSize.length; i ++ )
  5993. size *= workgroupSize[ i ];
  5994. this.dispatchCount = Math.ceil( count / size );
  5995. }
  5996. /**
  5997. * TODO
  5998. *
  5999. * @param {Function} callback - TODO.
  6000. * @return {ComputeNode} A reference to this node.
  6001. */
  6002. onInit( callback ) {
  6003. this.onInitFunction = callback;
  6004. return this;
  6005. }
  6006. /**
  6007. * The method execute the compute for this node.
  6008. *
  6009. * @param {NodeFrame} frame - A reference to the current node frame.
  6010. */
  6011. updateBefore( { renderer } ) {
  6012. renderer.compute( this );
  6013. }
  6014. generate( builder ) {
  6015. const { shaderStage } = builder;
  6016. if ( shaderStage === 'compute' ) {
  6017. const snippet = this.computeNode.build( builder, 'void' );
  6018. if ( snippet !== '' ) {
  6019. builder.addLineFlowCode( snippet, this );
  6020. }
  6021. }
  6022. }
  6023. }
  6024. /**
  6025. * TSL function for creating a compute node.
  6026. *
  6027. * @tsl
  6028. * @function
  6029. * @param {Node} node - TODO
  6030. * @param {number} count - TODO.
  6031. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6032. * @returns {AtomicFunctionNode}
  6033. */
  6034. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  6035. addMethodChaining( 'compute', compute );
  6036. /**
  6037. * This node can be used as a cache management component for another node.
  6038. * Caching is in general used by default in {@link NodeBuilder} but this node
  6039. * allows the usage of a shared parent cache during the build process.
  6040. *
  6041. * @augments Node
  6042. */
  6043. class CacheNode extends Node {
  6044. static get type() {
  6045. return 'CacheNode';
  6046. }
  6047. /**
  6048. * Constructs a new cache node.
  6049. *
  6050. * @param {Node} node - The node that should be cached.
  6051. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6052. */
  6053. constructor( node, parent = true ) {
  6054. super();
  6055. /**
  6056. * The node that should be cached.
  6057. *
  6058. * @type {Node}
  6059. */
  6060. this.node = node;
  6061. /**
  6062. * Whether this node refers to a shared parent cache or not.
  6063. *
  6064. * @type {boolean}
  6065. * @default true
  6066. */
  6067. this.parent = parent;
  6068. /**
  6069. * This flag can be used for type testing.
  6070. *
  6071. * @type {boolean}
  6072. * @readonly
  6073. * @default true
  6074. */
  6075. this.isCacheNode = true;
  6076. }
  6077. getNodeType( builder ) {
  6078. const previousCache = builder.getCache();
  6079. const cache = builder.getCacheFromNode( this, this.parent );
  6080. builder.setCache( cache );
  6081. const nodeType = this.node.getNodeType( builder );
  6082. builder.setCache( previousCache );
  6083. return nodeType;
  6084. }
  6085. build( builder, ...params ) {
  6086. const previousCache = builder.getCache();
  6087. const cache = builder.getCacheFromNode( this, this.parent );
  6088. builder.setCache( cache );
  6089. const data = this.node.build( builder, ...params );
  6090. builder.setCache( previousCache );
  6091. return data;
  6092. }
  6093. }
  6094. /**
  6095. * TSL function for creating a cache node.
  6096. *
  6097. * @tsl
  6098. * @function
  6099. * @param {Node} node - The node that should be cached.
  6100. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6101. * @returns {CacheNode}
  6102. */
  6103. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6104. addMethodChaining( 'cache', cache );
  6105. /**
  6106. * The class generates the code of a given node but returns another node in the output.
  6107. * This can be used to call a method or node that does not return a value, i.e.
  6108. * type `void` on an input where returning a value is required. Example:
  6109. *
  6110. * ```js
  6111. * material.colorNode = myColor.bypass( runVoidFn() )
  6112. *```
  6113. *
  6114. * @augments Node
  6115. */
  6116. class BypassNode extends Node {
  6117. static get type() {
  6118. return 'BypassNode';
  6119. }
  6120. /**
  6121. * Constructs a new bypass node.
  6122. *
  6123. * @param {Node} outputNode - The output node.
  6124. * @param {Node} callNode - The call node.
  6125. */
  6126. constructor( outputNode, callNode ) {
  6127. super();
  6128. /**
  6129. * This flag can be used for type testing.
  6130. *
  6131. * @type {boolean}
  6132. * @readonly
  6133. * @default true
  6134. */
  6135. this.isBypassNode = true;
  6136. /**
  6137. * The output node.
  6138. *
  6139. * @type {Node}
  6140. */
  6141. this.outputNode = outputNode;
  6142. /**
  6143. * The call node.
  6144. *
  6145. * @type {Node}
  6146. */
  6147. this.callNode = callNode;
  6148. }
  6149. getNodeType( builder ) {
  6150. return this.outputNode.getNodeType( builder );
  6151. }
  6152. generate( builder ) {
  6153. const snippet = this.callNode.build( builder, 'void' );
  6154. if ( snippet !== '' ) {
  6155. builder.addLineFlowCode( snippet, this );
  6156. }
  6157. return this.outputNode.build( builder );
  6158. }
  6159. }
  6160. /**
  6161. * TSL function for creating a bypass node.
  6162. *
  6163. * @tsl
  6164. * @function
  6165. * @param {Node} outputNode - The output node.
  6166. * @param {Node} callNode - The call node.
  6167. * @returns {BypassNode}
  6168. */
  6169. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  6170. addMethodChaining( 'bypass', bypass );
  6171. /**
  6172. * This node allows to remap a node value from one range into another. E.g a value of
  6173. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6174. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6175. *
  6176. * @augments Node
  6177. */
  6178. class RemapNode extends Node {
  6179. static get type() {
  6180. return 'RemapNode';
  6181. }
  6182. /**
  6183. * Constructs a new remap node.
  6184. *
  6185. * @param {Node} node - The node that should be remapped.
  6186. * @param {Node} inLowNode - The source or current lower bound of the range.
  6187. * @param {Node} inHighNode - The source or current upper bound of the range.
  6188. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6189. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6190. */
  6191. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6192. super();
  6193. /**
  6194. * The node that should be remapped.
  6195. *
  6196. * @type {Node}
  6197. */
  6198. this.node = node;
  6199. /**
  6200. * The source or current lower bound of the range.
  6201. *
  6202. * @type {Node}
  6203. */
  6204. this.inLowNode = inLowNode;
  6205. /**
  6206. * The source or current upper bound of the range.
  6207. *
  6208. * @type {Node}
  6209. */
  6210. this.inHighNode = inHighNode;
  6211. /**
  6212. * The target lower bound of the range.
  6213. *
  6214. * @type {Node}
  6215. * @default float(0)
  6216. */
  6217. this.outLowNode = outLowNode;
  6218. /**
  6219. * The target upper bound of the range.
  6220. *
  6221. * @type {Node}
  6222. * @default float(1)
  6223. */
  6224. this.outHighNode = outHighNode;
  6225. /**
  6226. * Whether the node value should be clamped before
  6227. * remapping it to the target range.
  6228. *
  6229. * @type {boolean}
  6230. * @default true
  6231. */
  6232. this.doClamp = true;
  6233. }
  6234. setup() {
  6235. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6236. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6237. if ( doClamp === true ) t = t.clamp();
  6238. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6239. }
  6240. }
  6241. /**
  6242. * TSL function for creating a remap node.
  6243. *
  6244. * @tsl
  6245. * @function
  6246. * @param {Node} node - The node that should be remapped.
  6247. * @param {Node} inLowNode - The source or current lower bound of the range.
  6248. * @param {Node} inHighNode - The source or current upper bound of the range.
  6249. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6250. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6251. * @returns {RemapNode}
  6252. */
  6253. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  6254. /**
  6255. * TSL function for creating a remap node, but with enabled clamping.
  6256. *
  6257. * @tsl
  6258. * @function
  6259. * @param {Node} node - The node that should be remapped.
  6260. * @param {Node} inLowNode - The source or current lower bound of the range.
  6261. * @param {Node} inHighNode - The source or current upper bound of the range.
  6262. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6263. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6264. * @returns {RemapNode}
  6265. */
  6266. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  6267. addMethodChaining( 'remap', remap );
  6268. addMethodChaining( 'remapClamp', remapClamp );
  6269. /**
  6270. * This class can be used to implement basic expressions in shader code.
  6271. * Basic examples for that are `return`, `continue` or `discard` statements.
  6272. *
  6273. * @augments Node
  6274. */
  6275. class ExpressionNode extends Node {
  6276. static get type() {
  6277. return 'ExpressionNode';
  6278. }
  6279. /**
  6280. * Constructs a new expression node.
  6281. *
  6282. * @param {string} [snippet=''] - The native code snippet.
  6283. * @param {string} [nodeType='void'] - The node type.
  6284. */
  6285. constructor( snippet = '', nodeType = 'void' ) {
  6286. super( nodeType );
  6287. /**
  6288. * The native code snippet.
  6289. *
  6290. * @type {string}
  6291. * @default ''
  6292. */
  6293. this.snippet = snippet;
  6294. }
  6295. generate( builder, output ) {
  6296. const type = this.getNodeType( builder );
  6297. const snippet = this.snippet;
  6298. if ( type === 'void' ) {
  6299. builder.addLineFlowCode( snippet, this );
  6300. } else {
  6301. return builder.format( snippet, type, output );
  6302. }
  6303. }
  6304. }
  6305. /**
  6306. * TSL function for creating an expression node.
  6307. *
  6308. * @tsl
  6309. * @function
  6310. * @param {string} [snippet=''] - The native code snippet.
  6311. * @param {string} [nodeType='void'] - The node type.
  6312. * @returns {ExpressionNode}
  6313. */
  6314. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  6315. /**
  6316. * Represents a `discard` shader operation in TSL.
  6317. *
  6318. * @tsl
  6319. * @function
  6320. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6321. * @return {Node} The `discard` expression.
  6322. */
  6323. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  6324. /**
  6325. * Represents a `return` shader operation in TSL.
  6326. *
  6327. * @tsl
  6328. * @function
  6329. * @return {ExpressionNode} The `return` expression.
  6330. */
  6331. const Return = () => expression( 'return' ).append();
  6332. addMethodChaining( 'discard', Discard );
  6333. /**
  6334. * Normally, tone mapping and color conversion happens automatically
  6335. * before outputting pixel too the default (screen) framebuffer. In certain
  6336. * post processing setups this happens to late because certain effects
  6337. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6338. * to apply tone mapping and color space conversion at an arbitrary point
  6339. * in the effect chain.
  6340. *
  6341. * When applying tone mapping and color space conversion manually with this node,
  6342. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6343. *
  6344. * ```js
  6345. * const postProcessing = new PostProcessing( renderer );
  6346. * postProcessing.outputColorTransform = false;
  6347. *
  6348. * const scenePass = pass( scene, camera );
  6349. * const outputPass = renderOutput( scenePass );
  6350. *
  6351. * postProcessing.outputNode = outputPass;
  6352. * ```
  6353. *
  6354. * @augments TempNode
  6355. */
  6356. class RenderOutputNode extends TempNode {
  6357. static get type() {
  6358. return 'RenderOutputNode';
  6359. }
  6360. /**
  6361. * Constructs a new render output node.
  6362. *
  6363. * @param {Node} colorNode - The color node to process.
  6364. * @param {?number} toneMapping - The tone mapping type.
  6365. * @param {?string} outputColorSpace - The output color space.
  6366. */
  6367. constructor( colorNode, toneMapping, outputColorSpace ) {
  6368. super( 'vec4' );
  6369. /**
  6370. * The color node to process.
  6371. *
  6372. * @type {Node}
  6373. */
  6374. this.colorNode = colorNode;
  6375. /**
  6376. * The tone mapping type.
  6377. *
  6378. * @type {?number}
  6379. */
  6380. this.toneMapping = toneMapping;
  6381. /**
  6382. * The output color space.
  6383. *
  6384. * @type {?string}
  6385. */
  6386. this.outputColorSpace = outputColorSpace;
  6387. /**
  6388. * This flag can be used for type testing.
  6389. *
  6390. * @type {boolean}
  6391. * @readonly
  6392. * @default true
  6393. */
  6394. this.isRenderOutputNode = true;
  6395. }
  6396. setup( { context } ) {
  6397. let outputNode = this.colorNode || context.color;
  6398. // tone mapping
  6399. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6400. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6401. if ( toneMapping !== NoToneMapping ) {
  6402. outputNode = outputNode.toneMapping( toneMapping );
  6403. }
  6404. // working to output color space
  6405. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6406. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6407. }
  6408. return outputNode;
  6409. }
  6410. }
  6411. /**
  6412. * TSL function for creating a posterize node.
  6413. *
  6414. * @tsl
  6415. * @function
  6416. * @param {Node} color - The color node to process.
  6417. * @param {?number} [toneMapping=null] - The tone mapping type.
  6418. * @param {?string} [outputColorSpace=null] - The output color space.
  6419. * @returns {RenderOutputNode}
  6420. */
  6421. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6422. addMethodChaining( 'renderOutput', renderOutput );
  6423. // Non-PURE exports list, side-effects are required here.
  6424. // TSL Base Syntax
  6425. function addNodeElement( name/*, nodeElement*/ ) {
  6426. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6427. }
  6428. /**
  6429. * Base class for representing shader attributes as nodes.
  6430. *
  6431. * @augments Node
  6432. */
  6433. class AttributeNode extends Node {
  6434. static get type() {
  6435. return 'AttributeNode';
  6436. }
  6437. /**
  6438. * Constructs a new attribute node.
  6439. *
  6440. * @param {string} attributeName - The name of the attribute.
  6441. * @param {?string} nodeType - The node type.
  6442. */
  6443. constructor( attributeName, nodeType = null ) {
  6444. super( nodeType );
  6445. /**
  6446. * `AttributeNode` sets this property to `true` by default.
  6447. *
  6448. * @type {boolean}
  6449. * @default true
  6450. */
  6451. this.global = true;
  6452. this._attributeName = attributeName;
  6453. }
  6454. getHash( builder ) {
  6455. return this.getAttributeName( builder );
  6456. }
  6457. getNodeType( builder ) {
  6458. let nodeType = this.nodeType;
  6459. if ( nodeType === null ) {
  6460. const attributeName = this.getAttributeName( builder );
  6461. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6462. const attribute = builder.geometry.getAttribute( attributeName );
  6463. nodeType = builder.getTypeFromAttribute( attribute );
  6464. } else {
  6465. nodeType = 'float';
  6466. }
  6467. }
  6468. return nodeType;
  6469. }
  6470. /**
  6471. * Sets the attribute name to the given value. The method can be
  6472. * overwritten in derived classes if the final name must be computed
  6473. * analytically.
  6474. *
  6475. * @param {string} attributeName - The name of the attribute.
  6476. * @return {AttributeNode} A reference to this node.
  6477. */
  6478. setAttributeName( attributeName ) {
  6479. this._attributeName = attributeName;
  6480. return this;
  6481. }
  6482. /**
  6483. * Returns the attribute name of this node. The method can be
  6484. * overwritten in derived classes if the final name must be computed
  6485. * analytically.
  6486. *
  6487. * @param {NodeBuilder} builder - The current node builder.
  6488. * @return {string} The attribute name.
  6489. */
  6490. getAttributeName( /*builder*/ ) {
  6491. return this._attributeName;
  6492. }
  6493. generate( builder ) {
  6494. const attributeName = this.getAttributeName( builder );
  6495. const nodeType = this.getNodeType( builder );
  6496. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6497. if ( geometryAttribute === true ) {
  6498. const attribute = builder.geometry.getAttribute( attributeName );
  6499. const attributeType = builder.getTypeFromAttribute( attribute );
  6500. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6501. if ( builder.shaderStage === 'vertex' ) {
  6502. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6503. } else {
  6504. const nodeVarying = varying( this );
  6505. return nodeVarying.build( builder, nodeType );
  6506. }
  6507. } else {
  6508. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6509. return builder.generateConst( nodeType );
  6510. }
  6511. }
  6512. serialize( data ) {
  6513. super.serialize( data );
  6514. data.global = this.global;
  6515. data._attributeName = this._attributeName;
  6516. }
  6517. deserialize( data ) {
  6518. super.deserialize( data );
  6519. this.global = data.global;
  6520. this._attributeName = data._attributeName;
  6521. }
  6522. }
  6523. /**
  6524. * TSL function for creating an attribute node.
  6525. *
  6526. * @tsl
  6527. * @function
  6528. * @param {string} name - The name of the attribute.
  6529. * @param {string} [nodeType] - The node type.
  6530. * @returns {AttributeNode}
  6531. */
  6532. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6533. /**
  6534. * TSL function for creating an uv attribute node with the given index.
  6535. *
  6536. * @tsl
  6537. * @function
  6538. * @param {number} [index=0] - The uv index.
  6539. * @return {AttributeNode<vec2>} The uv attribute node.
  6540. */
  6541. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6542. /**
  6543. * A node that represents the dimensions of a texture. The texture size is
  6544. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6545. * or `textureSize()`.
  6546. *
  6547. * @augments Node
  6548. */
  6549. class TextureSizeNode extends Node {
  6550. static get type() {
  6551. return 'TextureSizeNode';
  6552. }
  6553. /**
  6554. * Constructs a new texture size node.
  6555. *
  6556. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6557. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6558. */
  6559. constructor( textureNode, levelNode = null ) {
  6560. super( 'uvec2' );
  6561. /**
  6562. * This flag can be used for type testing.
  6563. *
  6564. * @type {boolean}
  6565. * @readonly
  6566. * @default true
  6567. */
  6568. this.isTextureSizeNode = true;
  6569. /**
  6570. * A texture node which size should be retrieved.
  6571. *
  6572. * @type {TextureNode}
  6573. */
  6574. this.textureNode = textureNode;
  6575. /**
  6576. * A level node which defines the requested mip.
  6577. *
  6578. * @type {Node<int>}
  6579. * @default null
  6580. */
  6581. this.levelNode = levelNode;
  6582. }
  6583. generate( builder, output ) {
  6584. const textureProperty = this.textureNode.build( builder, 'property' );
  6585. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6586. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6587. }
  6588. }
  6589. /**
  6590. * TSL function for creating a texture size node.
  6591. *
  6592. * @tsl
  6593. * @function
  6594. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6595. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6596. * @returns {TextureSizeNode}
  6597. */
  6598. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6599. /**
  6600. * A special type of uniform node that computes the
  6601. * maximum mipmap level for a given texture node.
  6602. *
  6603. * ```js
  6604. * const level = maxMipLevel( textureNode );
  6605. * ```
  6606. *
  6607. * @augments UniformNode
  6608. */
  6609. class MaxMipLevelNode extends UniformNode {
  6610. static get type() {
  6611. return 'MaxMipLevelNode';
  6612. }
  6613. /**
  6614. * Constructs a new max mip level node.
  6615. *
  6616. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6617. */
  6618. constructor( textureNode ) {
  6619. super( 0 );
  6620. /**
  6621. * The texture node to compute the max mip level for.
  6622. *
  6623. * @private
  6624. * @type {TextureNode}
  6625. */
  6626. this._textureNode = textureNode;
  6627. /**
  6628. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6629. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6630. *
  6631. * @type {string}
  6632. * @default 'frame'
  6633. */
  6634. this.updateType = NodeUpdateType.FRAME;
  6635. }
  6636. /**
  6637. * The texture node to compute the max mip level for.
  6638. *
  6639. * @readonly
  6640. * @type {TextureNode}
  6641. */
  6642. get textureNode() {
  6643. return this._textureNode;
  6644. }
  6645. /**
  6646. * The texture.
  6647. *
  6648. * @readonly
  6649. * @type {Texture}
  6650. */
  6651. get texture() {
  6652. return this._textureNode.value;
  6653. }
  6654. update() {
  6655. const texture = this.texture;
  6656. const images = texture.images;
  6657. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6658. if ( image && image.width !== undefined ) {
  6659. const { width, height } = image;
  6660. this.value = Math.log2( Math.max( width, height ) );
  6661. }
  6662. }
  6663. }
  6664. /**
  6665. * TSL function for creating a max mip level node.
  6666. *
  6667. * @tsl
  6668. * @function
  6669. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6670. * @returns {MaxMipLevelNode}
  6671. */
  6672. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6673. /**
  6674. * This type of uniform node represents a 2D texture.
  6675. *
  6676. * @augments UniformNode
  6677. */
  6678. class TextureNode extends UniformNode {
  6679. static get type() {
  6680. return 'TextureNode';
  6681. }
  6682. /**
  6683. * Constructs a new texture node.
  6684. *
  6685. * @param {Texture} value - The texture.
  6686. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  6687. * @param {?Node<int>} [levelNode=null] - The level node.
  6688. * @param {?Node<float>} [biasNode=null] - The bias node.
  6689. */
  6690. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6691. super( value );
  6692. /**
  6693. * This flag can be used for type testing.
  6694. *
  6695. * @type {boolean}
  6696. * @readonly
  6697. * @default true
  6698. */
  6699. this.isTextureNode = true;
  6700. /**
  6701. * Represents the texture coordinates.
  6702. *
  6703. * @type {?Node<vec2|vec3>}
  6704. * @default null
  6705. */
  6706. this.uvNode = uvNode;
  6707. /**
  6708. * Represents the mip level that should be selected.
  6709. *
  6710. * @type {?Node<int>}
  6711. * @default null
  6712. */
  6713. this.levelNode = levelNode;
  6714. /**
  6715. * Represents the bias to be applied during level-of-detail computation.
  6716. *
  6717. * @type {?Node<float>}
  6718. * @default null
  6719. */
  6720. this.biasNode = biasNode;
  6721. /**
  6722. * Represents a reference value a texture sample is compared to.
  6723. *
  6724. * @type {?Node<float>}
  6725. * @default null
  6726. */
  6727. this.compareNode = null;
  6728. /**
  6729. * When using texture arrays, the depth node defines the layer to select.
  6730. *
  6731. * @type {?Node<int>}
  6732. * @default null
  6733. */
  6734. this.depthNode = null;
  6735. /**
  6736. * When defined, a texture is sampled using explicit gradients.
  6737. *
  6738. * @type {?Array<Node<vec2>>}
  6739. * @default null
  6740. */
  6741. this.gradNode = null;
  6742. /**
  6743. * Whether texture values should be sampled or fetched.
  6744. *
  6745. * @type {boolean}
  6746. * @default true
  6747. */
  6748. this.sampler = true;
  6749. /**
  6750. * Whether the uv transformation matrix should be
  6751. * automatically updated or not. Use `setUpdateMatrix()`
  6752. * if you want to change the value of the property.
  6753. *
  6754. * @type {boolean}
  6755. * @default false
  6756. */
  6757. this.updateMatrix = false;
  6758. /**
  6759. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6760. * sets the value to `frame` when the uv transformation matrix should
  6761. * automatically be updated.
  6762. *
  6763. * @type {string}
  6764. * @default 'none'
  6765. */
  6766. this.updateType = NodeUpdateType.NONE;
  6767. /**
  6768. * The reference node.
  6769. *
  6770. * @type {?Node}
  6771. * @default null
  6772. */
  6773. this.referenceNode = null;
  6774. /**
  6775. * The texture value is stored in a private property.
  6776. *
  6777. * @private
  6778. * @type {Texture}
  6779. */
  6780. this._value = value;
  6781. /**
  6782. * The uniform node that represents the uv transformation matrix.
  6783. *
  6784. * @private
  6785. * @type {?UniformNode<mat3>}
  6786. */
  6787. this._matrixUniform = null;
  6788. this.setUpdateMatrix( uvNode === null );
  6789. }
  6790. set value( value ) {
  6791. if ( this.referenceNode ) {
  6792. this.referenceNode.value = value;
  6793. } else {
  6794. this._value = value;
  6795. }
  6796. }
  6797. /**
  6798. * The texture value.
  6799. *
  6800. * @type {Texture}
  6801. */
  6802. get value() {
  6803. return this.referenceNode ? this.referenceNode.value : this._value;
  6804. }
  6805. /**
  6806. * Overwritten since the uniform hash is defined by the texture's UUID.
  6807. *
  6808. * @param {NodeBuilder} builder - The current node builder.
  6809. * @return {string} The uniform hash.
  6810. */
  6811. getUniformHash( /*builder*/ ) {
  6812. return this.value.uuid;
  6813. }
  6814. /**
  6815. * Overwritten since the node type is inferred from the texture type.
  6816. *
  6817. * @param {NodeBuilder} builder - The current node builder.
  6818. * @return {string} The node type.
  6819. */
  6820. getNodeType( /*builder*/ ) {
  6821. if ( this.value.isDepthTexture === true ) return 'float';
  6822. if ( this.value.type === UnsignedIntType ) {
  6823. return 'uvec4';
  6824. } else if ( this.value.type === IntType ) {
  6825. return 'ivec4';
  6826. }
  6827. return 'vec4';
  6828. }
  6829. /**
  6830. * Overwrites the default implementation to return a fixed value `'texture'`.
  6831. *
  6832. * @param {NodeBuilder} builder - The current node builder.
  6833. * @return {string} The input type.
  6834. */
  6835. getInputType( /*builder*/ ) {
  6836. return 'texture';
  6837. }
  6838. /**
  6839. * Returns a default uvs based on the current texture's channel.
  6840. *
  6841. * @return {AttributeNode<vec2>} The default uvs.
  6842. */
  6843. getDefaultUV() {
  6844. return uv( this.value.channel );
  6845. }
  6846. /**
  6847. * Overwritten to always return the texture reference of the node.
  6848. *
  6849. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6850. * @return {Texture} The texture reference.
  6851. */
  6852. updateReference( /*state*/ ) {
  6853. return this.value;
  6854. }
  6855. /**
  6856. * Transforms the given uv node with the texture transformation matrix.
  6857. *
  6858. * @param {Node} uvNode - The uv node to transform.
  6859. * @return {Node} The transformed uv node.
  6860. */
  6861. getTransformedUV( uvNode ) {
  6862. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6863. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6864. }
  6865. /**
  6866. * Defines whether the uv transformation matrix should automatically be updated or not.
  6867. *
  6868. * @param {boolean} value - The update toggle.
  6869. * @return {TextureNode} A reference to this node.
  6870. */
  6871. setUpdateMatrix( value ) {
  6872. this.updateMatrix = value;
  6873. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6874. return this;
  6875. }
  6876. /**
  6877. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6878. * to modify the uv node for correct sampling.
  6879. *
  6880. * @param {NodeBuilder} builder - The current node builder.
  6881. * @param {Node} uvNode - The uv node to setup.
  6882. * @return {Node} The updated uv node.
  6883. */
  6884. setupUV( builder, uvNode ) {
  6885. const texture = this.value;
  6886. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6887. if ( this.sampler ) {
  6888. uvNode = uvNode.flipY();
  6889. } else {
  6890. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6891. }
  6892. }
  6893. return uvNode;
  6894. }
  6895. /**
  6896. * Setups texture node by preparing the internal nodes for code generation.
  6897. *
  6898. * @param {NodeBuilder} builder - The current node builder.
  6899. */
  6900. setup( builder ) {
  6901. const properties = builder.getNodeProperties( this );
  6902. properties.referenceNode = this.referenceNode;
  6903. //
  6904. const texture = this.value;
  6905. if ( ! texture || texture.isTexture !== true ) {
  6906. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6907. }
  6908. //
  6909. let uvNode = this.uvNode;
  6910. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6911. uvNode = builder.context.getUV( this );
  6912. }
  6913. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6914. if ( this.updateMatrix === true ) {
  6915. uvNode = this.getTransformedUV( uvNode );
  6916. }
  6917. uvNode = this.setupUV( builder, uvNode );
  6918. //
  6919. let levelNode = this.levelNode;
  6920. if ( levelNode === null && builder.context.getTextureLevel ) {
  6921. levelNode = builder.context.getTextureLevel( this );
  6922. }
  6923. //
  6924. properties.uvNode = uvNode;
  6925. properties.levelNode = levelNode;
  6926. properties.biasNode = this.biasNode;
  6927. properties.compareNode = this.compareNode;
  6928. properties.gradNode = this.gradNode;
  6929. properties.depthNode = this.depthNode;
  6930. }
  6931. /**
  6932. * Generates the uv code snippet.
  6933. *
  6934. * @param {NodeBuilder} builder - The current node builder.
  6935. * @param {Node} uvNode - The uv node to generate code for.
  6936. * @return {string} The generated code snippet.
  6937. */
  6938. generateUV( builder, uvNode ) {
  6939. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6940. }
  6941. /**
  6942. * Generates the snippet for the texture sampling.
  6943. *
  6944. * @param {NodeBuilder} builder - The current node builder.
  6945. * @param {string} textureProperty - The texture property.
  6946. * @param {string} uvSnippet - The uv snippet.
  6947. * @param {?string} levelSnippet - The level snippet.
  6948. * @param {?string} biasSnippet - The bias snippet.
  6949. * @param {?string} depthSnippet - The depth snippet.
  6950. * @param {?string} compareSnippet - The compare snippet.
  6951. * @param {?Array<string>} gradSnippet - The grad snippet.
  6952. * @return {string} The generated code snippet.
  6953. */
  6954. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6955. const texture = this.value;
  6956. let snippet;
  6957. if ( levelSnippet ) {
  6958. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6959. } else if ( biasSnippet ) {
  6960. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6961. } else if ( gradSnippet ) {
  6962. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6963. } else if ( compareSnippet ) {
  6964. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6965. } else if ( this.sampler === false ) {
  6966. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6967. } else {
  6968. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6969. }
  6970. return snippet;
  6971. }
  6972. /**
  6973. * Generates the code snippet of the texture node.
  6974. *
  6975. * @param {NodeBuilder} builder - The current node builder.
  6976. * @param {string} output - The current output.
  6977. * @return {string} The generated code snippet.
  6978. */
  6979. generate( builder, output ) {
  6980. const texture = this.value;
  6981. const properties = builder.getNodeProperties( this );
  6982. const textureProperty = super.generate( builder, 'property' );
  6983. if ( /^sampler/.test( output ) ) {
  6984. return textureProperty + '_sampler';
  6985. } else if ( builder.isReference( output ) ) {
  6986. return textureProperty;
  6987. } else {
  6988. const nodeData = builder.getDataFromNode( this );
  6989. let propertyName = nodeData.propertyName;
  6990. if ( propertyName === undefined ) {
  6991. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6992. const uvSnippet = this.generateUV( builder, uvNode );
  6993. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6994. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6995. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6996. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6997. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6998. const nodeVar = builder.getVarFromNode( this );
  6999. propertyName = builder.getPropertyName( nodeVar );
  7000. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7001. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7002. nodeData.snippet = snippet;
  7003. nodeData.propertyName = propertyName;
  7004. }
  7005. let snippet = propertyName;
  7006. const nodeType = this.getNodeType( builder );
  7007. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7008. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7009. }
  7010. return builder.format( snippet, nodeType, output );
  7011. }
  7012. }
  7013. /**
  7014. * Sets the sampler value.
  7015. *
  7016. * @param {boolean} value - The sampler value to set.
  7017. * @return {TextureNode} A reference to this texture node.
  7018. */
  7019. setSampler( value ) {
  7020. this.sampler = value;
  7021. return this;
  7022. }
  7023. /**
  7024. * Returns the sampler value.
  7025. *
  7026. * @return {boolean} The sampler value.
  7027. */
  7028. getSampler() {
  7029. return this.sampler;
  7030. }
  7031. // @TODO: Move to TSL
  7032. /**
  7033. * @function
  7034. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7035. *
  7036. * @param {Node} uvNode - The uv node.
  7037. * @return {TextureNode} A texture node representing the texture sample.
  7038. */
  7039. uv( uvNode ) { // @deprecated, r172
  7040. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7041. return this.sample( uvNode );
  7042. }
  7043. /**
  7044. * Samples the texture with the given uv node.
  7045. *
  7046. * @param {Node} uvNode - The uv node.
  7047. * @return {TextureNode} A texture node representing the texture sample.
  7048. */
  7049. sample( uvNode ) {
  7050. const textureNode = this.clone();
  7051. textureNode.uvNode = nodeObject( uvNode );
  7052. textureNode.referenceNode = this.getSelf();
  7053. return nodeObject( textureNode );
  7054. }
  7055. /**
  7056. * Samples a blurred version of the texture by defining an internal bias.
  7057. *
  7058. * @param {Node<float>} amountNode - How blurred the texture should be.
  7059. * @return {TextureNode} A texture node representing the texture sample.
  7060. */
  7061. blur( amountNode ) {
  7062. const textureNode = this.clone();
  7063. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7064. textureNode.referenceNode = this.getSelf();
  7065. const map = textureNode.value;
  7066. if ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) {
  7067. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7068. textureNode.biasNode = null;
  7069. }
  7070. return nodeObject( textureNode );
  7071. }
  7072. /**
  7073. * Samples a specific mip of the texture.
  7074. *
  7075. * @param {Node<int>} levelNode - The mip level to sample.
  7076. * @return {TextureNode} A texture node representing the texture sample.
  7077. */
  7078. level( levelNode ) {
  7079. const textureNode = this.clone();
  7080. textureNode.levelNode = nodeObject( levelNode );
  7081. textureNode.referenceNode = this.getSelf();
  7082. return nodeObject( textureNode );
  7083. }
  7084. /**
  7085. * Returns the texture size of the requested level.
  7086. *
  7087. * @param {Node<int>} levelNode - The level to compute the size for.
  7088. * @return {TextureSizeNode} The texture size.
  7089. */
  7090. size( levelNode ) {
  7091. return textureSize( this, levelNode );
  7092. }
  7093. /**
  7094. * Samples the texture with the given bias.
  7095. *
  7096. * @param {Node<float>} biasNode - The bias node.
  7097. * @return {TextureNode} A texture node representing the texture sample.
  7098. */
  7099. bias( biasNode ) {
  7100. const textureNode = this.clone();
  7101. textureNode.biasNode = nodeObject( biasNode );
  7102. textureNode.referenceNode = this.getSelf();
  7103. return nodeObject( textureNode );
  7104. }
  7105. /**
  7106. * Samples the texture by executing a compare operation.
  7107. *
  7108. * @param {Node<float>} compareNode - The node that defines the compare value.
  7109. * @return {TextureNode} A texture node representing the texture sample.
  7110. */
  7111. compare( compareNode ) {
  7112. const textureNode = this.clone();
  7113. textureNode.compareNode = nodeObject( compareNode );
  7114. textureNode.referenceNode = this.getSelf();
  7115. return nodeObject( textureNode );
  7116. }
  7117. /**
  7118. * Samples the texture using an explicit gradient.
  7119. *
  7120. * @param {Node<vec2>} gradNodeX - The gradX node.
  7121. * @param {Node<vec2>} gradNodeY - The gradY node.
  7122. * @return {TextureNode} A texture node representing the texture sample.
  7123. */
  7124. grad( gradNodeX, gradNodeY ) {
  7125. const textureNode = this.clone();
  7126. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7127. textureNode.referenceNode = this.getSelf();
  7128. return nodeObject( textureNode );
  7129. }
  7130. /**
  7131. * Samples the texture by defining a depth node.
  7132. *
  7133. * @param {Node<int>} depthNode - The depth node.
  7134. * @return {TextureNode} A texture node representing the texture sample.
  7135. */
  7136. depth( depthNode ) {
  7137. const textureNode = this.clone();
  7138. textureNode.depthNode = nodeObject( depthNode );
  7139. textureNode.referenceNode = this.getSelf();
  7140. return nodeObject( textureNode );
  7141. }
  7142. // --
  7143. serialize( data ) {
  7144. super.serialize( data );
  7145. data.value = this.value.toJSON( data.meta ).uuid;
  7146. data.sampler = this.sampler;
  7147. data.updateMatrix = this.updateMatrix;
  7148. data.updateType = this.updateType;
  7149. }
  7150. deserialize( data ) {
  7151. super.deserialize( data );
  7152. this.value = data.meta.textures[ data.value ];
  7153. this.sampler = data.sampler;
  7154. this.updateMatrix = data.updateMatrix;
  7155. this.updateType = data.updateType;
  7156. }
  7157. /**
  7158. * The update is used to implement the update of the uv transformation matrix.
  7159. */
  7160. update() {
  7161. const texture = this.value;
  7162. const matrixUniform = this._matrixUniform;
  7163. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7164. if ( texture.matrixAutoUpdate === true ) {
  7165. texture.updateMatrix();
  7166. }
  7167. }
  7168. /**
  7169. * Clones the texture node.
  7170. *
  7171. * @return {TextureNode} The cloned texture node.
  7172. */
  7173. clone() {
  7174. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7175. newNode.sampler = this.sampler;
  7176. return newNode;
  7177. }
  7178. }
  7179. /**
  7180. * TSL function for creating a texture node.
  7181. *
  7182. * @tsl
  7183. * @function
  7184. * @param {Texture} value - The texture.
  7185. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7186. * @param {?Node<int>} [levelNode=null] - The level node.
  7187. * @param {?Node<float>} [biasNode=null] - The bias node.
  7188. * @returns {TextureNode}
  7189. */
  7190. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  7191. /**
  7192. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7193. *
  7194. * @tsl
  7195. * @function
  7196. * @param {Texture} value - The texture.
  7197. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7198. * @param {?Node<int>} [levelNode=null] - The level node.
  7199. * @param {?Node<float>} [biasNode=null] - The bias node.
  7200. * @returns {TextureNode}
  7201. */
  7202. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7203. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7204. /**
  7205. * Converts a texture or texture node to a sampler.
  7206. *
  7207. * @tsl
  7208. * @function
  7209. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7210. * @returns {Node}
  7211. */
  7212. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  7213. /**
  7214. * Converts a texture or texture node to a sampler comparison.
  7215. *
  7216. * @tsl
  7217. * @function
  7218. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7219. * @returns {Node}
  7220. */
  7221. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  7222. /**
  7223. * A special type of uniform node which represents array-like data
  7224. * as uniform buffers. The access usually happens via `element()`
  7225. * which returns an instance of {@link ArrayElementNode}. For example:
  7226. *
  7227. * ```js
  7228. * const bufferNode = buffer( array, 'mat4', count );
  7229. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7230. * ```
  7231. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7232. * since it handles more input types and automatically cares about buffer paddings.
  7233. *
  7234. * @augments UniformNode
  7235. */
  7236. class BufferNode extends UniformNode {
  7237. static get type() {
  7238. return 'BufferNode';
  7239. }
  7240. /**
  7241. * Constructs a new buffer node.
  7242. *
  7243. * @param {Array<number>} value - Array-like buffer data.
  7244. * @param {string} bufferType - The data type of the buffer.
  7245. * @param {number} [bufferCount=0] - The count of buffer elements.
  7246. */
  7247. constructor( value, bufferType, bufferCount = 0 ) {
  7248. super( value, bufferType );
  7249. /**
  7250. * This flag can be used for type testing.
  7251. *
  7252. * @type {boolean}
  7253. * @readonly
  7254. * @default true
  7255. */
  7256. this.isBufferNode = true;
  7257. /**
  7258. * The data type of the buffer.
  7259. *
  7260. * @type {string}
  7261. */
  7262. this.bufferType = bufferType;
  7263. /**
  7264. * The uniform node that holds the value of the reference node.
  7265. *
  7266. * @type {number}
  7267. * @default 0
  7268. */
  7269. this.bufferCount = bufferCount;
  7270. }
  7271. /**
  7272. * The data type of the buffer elements.
  7273. *
  7274. * @param {NodeBuilder} builder - The current node builder.
  7275. * @return {string} The element type.
  7276. */
  7277. getElementType( builder ) {
  7278. return this.getNodeType( builder );
  7279. }
  7280. /**
  7281. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7282. *
  7283. * @param {NodeBuilder} builder - The current node builder.
  7284. * @return {string} The input type.
  7285. */
  7286. getInputType( /*builder*/ ) {
  7287. return 'buffer';
  7288. }
  7289. }
  7290. /**
  7291. * TSL function for creating a buffer node.
  7292. *
  7293. * @tsl
  7294. * @function
  7295. * @param {Array} value - Array-like buffer data.
  7296. * @param {string} type - The data type of a buffer element.
  7297. * @param {number} count - The count of buffer elements.
  7298. * @returns {BufferNode}
  7299. */
  7300. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7301. /**
  7302. * Represents the element access on uniform array nodes.
  7303. *
  7304. * @augments ArrayElementNode
  7305. */
  7306. class UniformArrayElementNode extends ArrayElementNode {
  7307. static get type() {
  7308. return 'UniformArrayElementNode';
  7309. }
  7310. /**
  7311. * Constructs a new buffer node.
  7312. *
  7313. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7314. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7315. */
  7316. constructor( uniformArrayNode, indexNode ) {
  7317. super( uniformArrayNode, indexNode );
  7318. /**
  7319. * This flag can be used for type testing.
  7320. *
  7321. * @type {boolean}
  7322. * @readonly
  7323. * @default true
  7324. */
  7325. this.isArrayBufferElementNode = true;
  7326. }
  7327. generate( builder ) {
  7328. const snippet = super.generate( builder );
  7329. const type = this.getNodeType();
  7330. const paddedType = this.node.getPaddedType();
  7331. return builder.format( snippet, paddedType, type );
  7332. }
  7333. }
  7334. /**
  7335. * Similar to {@link BufferNode} this module represents array-like data as
  7336. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7337. * data types in the array (e.g `three.js` primitives) and automatically
  7338. * manage buffer padding. It should be the first choice when working with
  7339. * uniforms buffers.
  7340. * ```js
  7341. * const tintColors = uniformArray( [
  7342. * new Color( 1, 0, 0 ),
  7343. * new Color( 0, 1, 0 ),
  7344. * new Color( 0, 0, 1 )
  7345. * ], 'color' );
  7346. *
  7347. * const redColor = tintColors.element( 0 );
  7348. *
  7349. * @augments BufferNode
  7350. */
  7351. class UniformArrayNode extends BufferNode {
  7352. static get type() {
  7353. return 'UniformArrayNode';
  7354. }
  7355. /**
  7356. * Constructs a new uniform array node.
  7357. *
  7358. * @param {Array<any>} value - Array holding the buffer data.
  7359. * @param {?string} [elementType=null] - The data type of a buffer element.
  7360. */
  7361. constructor( value, elementType = null ) {
  7362. super( null );
  7363. /**
  7364. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7365. * hold number primitives as well as three.js objects like vectors, matrices
  7366. * or colors.
  7367. *
  7368. * @type {Array<any>}
  7369. */
  7370. this.array = value;
  7371. /**
  7372. * The data type of an array element.
  7373. *
  7374. * @type {string}
  7375. */
  7376. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7377. /**
  7378. * The padded type. Uniform buffers must conform to a certain buffer layout
  7379. * so a separate type is computed to ensure correct buffer size.
  7380. *
  7381. * @type {string}
  7382. */
  7383. this.paddedType = this.getPaddedType();
  7384. /**
  7385. * Overwritten since uniform array nodes are updated per render.
  7386. *
  7387. * @type {string}
  7388. * @default 'render'
  7389. */
  7390. this.updateType = NodeUpdateType.RENDER;
  7391. /**
  7392. * This flag can be used for type testing.
  7393. *
  7394. * @type {boolean}
  7395. * @readonly
  7396. * @default true
  7397. */
  7398. this.isArrayBufferNode = true;
  7399. }
  7400. /**
  7401. * This method is overwritten since the node type is inferred from the
  7402. * {@link UniformArrayNode#paddedType}.
  7403. *
  7404. * @param {NodeBuilder} builder - The current node builder.
  7405. * @return {string} The node type.
  7406. */
  7407. getNodeType( /*builder*/ ) {
  7408. return this.paddedType;
  7409. }
  7410. /**
  7411. * The data type of the array elements.
  7412. *
  7413. * @param {NodeBuilder} builder - The current node builder.
  7414. * @return {string} The element type.
  7415. */
  7416. getElementType() {
  7417. return this.elementType;
  7418. }
  7419. /**
  7420. * Returns the padded type based on the element type.
  7421. *
  7422. * @return {string} The padded type.
  7423. */
  7424. getPaddedType() {
  7425. const elementType = this.elementType;
  7426. let paddedType = 'vec4';
  7427. if ( elementType === 'mat2' ) {
  7428. paddedType = 'mat2';
  7429. } else if ( /mat/.test( elementType ) === true ) {
  7430. paddedType = 'mat4';
  7431. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7432. paddedType = 'ivec4';
  7433. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7434. paddedType = 'uvec4';
  7435. }
  7436. return paddedType;
  7437. }
  7438. /**
  7439. * The update makes sure to correctly transfer the data from the (complex) objects
  7440. * in the array to the internal, correctly padded value buffer.
  7441. *
  7442. * @param {NodeFrame} frame - A reference to the current node frame.
  7443. */
  7444. update( /*frame*/ ) {
  7445. const { array, value } = this;
  7446. const elementType = this.elementType;
  7447. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7448. for ( let i = 0; i < array.length; i ++ ) {
  7449. const index = i * 4;
  7450. value[ index ] = array[ i ];
  7451. }
  7452. } else if ( elementType === 'color' ) {
  7453. for ( let i = 0; i < array.length; i ++ ) {
  7454. const index = i * 4;
  7455. const vector = array[ i ];
  7456. value[ index ] = vector.r;
  7457. value[ index + 1 ] = vector.g;
  7458. value[ index + 2 ] = vector.b || 0;
  7459. //value[ index + 3 ] = vector.a || 0;
  7460. }
  7461. } else if ( elementType === 'mat2' ) {
  7462. for ( let i = 0; i < array.length; i ++ ) {
  7463. const index = i * 4;
  7464. const matrix = array[ i ];
  7465. value[ index ] = matrix.elements[ 0 ];
  7466. value[ index + 1 ] = matrix.elements[ 1 ];
  7467. value[ index + 2 ] = matrix.elements[ 2 ];
  7468. value[ index + 3 ] = matrix.elements[ 3 ];
  7469. }
  7470. } else if ( elementType === 'mat3' ) {
  7471. for ( let i = 0; i < array.length; i ++ ) {
  7472. const index = i * 16;
  7473. const matrix = array[ i ];
  7474. value[ index ] = matrix.elements[ 0 ];
  7475. value[ index + 1 ] = matrix.elements[ 1 ];
  7476. value[ index + 2 ] = matrix.elements[ 2 ];
  7477. value[ index + 4 ] = matrix.elements[ 3 ];
  7478. value[ index + 5 ] = matrix.elements[ 4 ];
  7479. value[ index + 6 ] = matrix.elements[ 5 ];
  7480. value[ index + 8 ] = matrix.elements[ 6 ];
  7481. value[ index + 9 ] = matrix.elements[ 7 ];
  7482. value[ index + 10 ] = matrix.elements[ 8 ];
  7483. value[ index + 15 ] = 1;
  7484. }
  7485. } else if ( elementType === 'mat4' ) {
  7486. for ( let i = 0; i < array.length; i ++ ) {
  7487. const index = i * 16;
  7488. const matrix = array[ i ];
  7489. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7490. value[ index + i ] = matrix.elements[ i ];
  7491. }
  7492. }
  7493. } else {
  7494. for ( let i = 0; i < array.length; i ++ ) {
  7495. const index = i * 4;
  7496. const vector = array[ i ];
  7497. value[ index ] = vector.x;
  7498. value[ index + 1 ] = vector.y;
  7499. value[ index + 2 ] = vector.z || 0;
  7500. value[ index + 3 ] = vector.w || 0;
  7501. }
  7502. }
  7503. }
  7504. /**
  7505. * Implement the value buffer creation based on the array data.
  7506. *
  7507. * @param {NodeBuilder} builder - A reference to the current node builder.
  7508. * @return {null}
  7509. */
  7510. setup( builder ) {
  7511. const length = this.array.length;
  7512. const elementType = this.elementType;
  7513. let arrayType = Float32Array;
  7514. const paddedType = this.paddedType;
  7515. const paddedElementLength = builder.getTypeLength( paddedType );
  7516. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7517. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7518. this.value = new arrayType( length * paddedElementLength );
  7519. this.bufferCount = length;
  7520. this.bufferType = paddedType;
  7521. return super.setup( builder );
  7522. }
  7523. /**
  7524. * Overwrites the default `element()` method to provide element access
  7525. * based on {@link UniformArrayNode}.
  7526. *
  7527. * @param {IndexNode} indexNode - The index node.
  7528. * @return {UniformArrayElementNode}
  7529. */
  7530. element( indexNode ) {
  7531. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7532. }
  7533. }
  7534. /**
  7535. * TSL function for creating an uniform array node.
  7536. *
  7537. * @tsl
  7538. * @function
  7539. * @param {Array<any>} values - Array-like data.
  7540. * @param {?string} [nodeType] - The data type of the array elements.
  7541. * @returns {UniformArrayNode}
  7542. */
  7543. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7544. /**
  7545. * @tsl
  7546. * @function
  7547. * @deprecated since r168. Use {@link uniformArray} instead.
  7548. *
  7549. * @param {Array<any>} values - Array-like data.
  7550. * @param {string} nodeType - The data type of the array elements.
  7551. * @returns {UniformArrayNode}
  7552. */
  7553. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7554. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7555. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7556. };
  7557. /**
  7558. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7559. *
  7560. * @tsl
  7561. * @type {UniformNode<uint>}
  7562. */
  7563. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7564. /**
  7565. * TSL object that represents the `near` value of the camera used for the current render.
  7566. *
  7567. * @tsl
  7568. * @type {UniformNode<float>}
  7569. */
  7570. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7571. /**
  7572. * TSL object that represents the `far` value of the camera used for the current render.
  7573. *
  7574. * @tsl
  7575. * @type {UniformNode<float>}
  7576. */
  7577. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7578. /**
  7579. * TSL object that represents the projection matrix of the camera used for the current render.
  7580. *
  7581. * @tsl
  7582. * @type {UniformNode<mat4>}
  7583. */
  7584. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7585. let cameraProjectionMatrix;
  7586. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7587. const matrices = [];
  7588. for ( const subCamera of camera.cameras ) {
  7589. matrices.push( subCamera.projectionMatrix );
  7590. }
  7591. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7592. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7593. } else {
  7594. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7595. }
  7596. return cameraProjectionMatrix;
  7597. } ).once() )();
  7598. /**
  7599. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7600. *
  7601. * @tsl
  7602. * @type {UniformNode<mat4>}
  7603. */
  7604. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7605. /**
  7606. * TSL object that represents the view matrix of the camera used for the current render.
  7607. *
  7608. * @tsl
  7609. * @type {UniformNode<mat4>}
  7610. */
  7611. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7612. let cameraViewMatrix;
  7613. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7614. const matrices = [];
  7615. for ( const subCamera of camera.cameras ) {
  7616. matrices.push( subCamera.matrixWorldInverse );
  7617. }
  7618. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7619. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7620. } else {
  7621. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7622. }
  7623. return cameraViewMatrix;
  7624. } ).once() )();
  7625. /**
  7626. * TSL object that represents the world matrix of the camera used for the current render.
  7627. *
  7628. * @tsl
  7629. * @type {UniformNode<mat4>}
  7630. */
  7631. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7632. /**
  7633. * TSL object that represents the normal matrix of the camera used for the current render.
  7634. *
  7635. * @tsl
  7636. * @type {UniformNode<mat3>}
  7637. */
  7638. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7639. /**
  7640. * TSL object that represents the position in world space of the camera used for the current render.
  7641. *
  7642. * @tsl
  7643. * @type {UniformNode<vec3>}
  7644. */
  7645. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7646. const _sphere = /*@__PURE__*/ new Sphere();
  7647. /**
  7648. * This node can be used to access transformation related metrics of 3D objects.
  7649. * Depending on the selected scope, a different metric is represented as a uniform
  7650. * in the shader. The following scopes are supported:
  7651. *
  7652. * - `POSITION`: The object's position in world space.
  7653. * - `VIEW_POSITION`: The object's position in view/camera space.
  7654. * - `DIRECTION`: The object's direction in world space.
  7655. * - `SCALE`: The object's scale in world space.
  7656. * - `WORLD_MATRIX`: The object's matrix in world space.
  7657. *
  7658. * @augments Node
  7659. */
  7660. class Object3DNode extends Node {
  7661. static get type() {
  7662. return 'Object3DNode';
  7663. }
  7664. /**
  7665. * Constructs a new object 3D node.
  7666. *
  7667. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7668. * @param {?Object3D} [object3d=null] - The 3D object.
  7669. */
  7670. constructor( scope, object3d = null ) {
  7671. super();
  7672. /**
  7673. * The node reports a different type of transformation depending on the scope.
  7674. *
  7675. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7676. */
  7677. this.scope = scope;
  7678. /**
  7679. * The 3D object.
  7680. *
  7681. * @type {?Object3D}
  7682. * @default null
  7683. */
  7684. this.object3d = object3d;
  7685. /**
  7686. * Overwritten since this type of node is updated per object.
  7687. *
  7688. * @type {string}
  7689. * @default 'object'
  7690. */
  7691. this.updateType = NodeUpdateType.OBJECT;
  7692. /**
  7693. * Holds the value of the node as a uniform.
  7694. *
  7695. * @private
  7696. * @type {UniformNode}
  7697. */
  7698. this._uniformNode = new UniformNode( null );
  7699. }
  7700. /**
  7701. * Overwritten since the node type is inferred from the scope.
  7702. *
  7703. * @return {string} The node type.
  7704. */
  7705. getNodeType() {
  7706. const scope = this.scope;
  7707. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7708. return 'mat4';
  7709. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7710. return 'vec3';
  7711. } else if ( scope === Object3DNode.RADIUS ) {
  7712. return 'float';
  7713. }
  7714. }
  7715. /**
  7716. * Updates the uniform value depending on the scope.
  7717. *
  7718. * @param {NodeFrame} frame - The current node frame.
  7719. */
  7720. update( frame ) {
  7721. const object = this.object3d;
  7722. const uniformNode = this._uniformNode;
  7723. const scope = this.scope;
  7724. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7725. uniformNode.value = object.matrixWorld;
  7726. } else if ( scope === Object3DNode.POSITION ) {
  7727. uniformNode.value = uniformNode.value || new Vector3();
  7728. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7729. } else if ( scope === Object3DNode.SCALE ) {
  7730. uniformNode.value = uniformNode.value || new Vector3();
  7731. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7732. } else if ( scope === Object3DNode.DIRECTION ) {
  7733. uniformNode.value = uniformNode.value || new Vector3();
  7734. object.getWorldDirection( uniformNode.value );
  7735. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7736. const camera = frame.camera;
  7737. uniformNode.value = uniformNode.value || new Vector3();
  7738. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7739. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7740. } else if ( scope === Object3DNode.RADIUS ) {
  7741. const geometry = frame.object.geometry;
  7742. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7743. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7744. uniformNode.value = _sphere.radius;
  7745. }
  7746. }
  7747. /**
  7748. * Generates the code snippet of the uniform node. The node type of the uniform
  7749. * node also depends on the selected scope.
  7750. *
  7751. * @param {NodeBuilder} builder - The current node builder.
  7752. * @return {string} The generated code snippet.
  7753. */
  7754. generate( builder ) {
  7755. const scope = this.scope;
  7756. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7757. this._uniformNode.nodeType = 'mat4';
  7758. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7759. this._uniformNode.nodeType = 'vec3';
  7760. } else if ( scope === Object3DNode.RADIUS ) {
  7761. this._uniformNode.nodeType = 'float';
  7762. }
  7763. return this._uniformNode.build( builder );
  7764. }
  7765. serialize( data ) {
  7766. super.serialize( data );
  7767. data.scope = this.scope;
  7768. }
  7769. deserialize( data ) {
  7770. super.deserialize( data );
  7771. this.scope = data.scope;
  7772. }
  7773. }
  7774. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7775. Object3DNode.POSITION = 'position';
  7776. Object3DNode.SCALE = 'scale';
  7777. Object3DNode.VIEW_POSITION = 'viewPosition';
  7778. Object3DNode.DIRECTION = 'direction';
  7779. Object3DNode.RADIUS = 'radius';
  7780. /**
  7781. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7782. *
  7783. * @tsl
  7784. * @function
  7785. * @param {?Object3D} [object3d=null] - The 3D object.
  7786. * @returns {Object3DNode<vec3>}
  7787. */
  7788. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7789. /**
  7790. * TSL function for creating an object 3D node that represents the object's world matrix.
  7791. *
  7792. * @tsl
  7793. * @function
  7794. * @param {?Object3D} [object3d=null] - The 3D object.
  7795. * @returns {Object3DNode<mat4>}
  7796. */
  7797. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7798. /**
  7799. * TSL function for creating an object 3D node that represents the object's position in world space.
  7800. *
  7801. * @tsl
  7802. * @function
  7803. * @param {?Object3D} [object3d=null] - The 3D object.
  7804. * @returns {Object3DNode<vec3>}
  7805. */
  7806. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7807. /**
  7808. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7809. *
  7810. * @tsl
  7811. * @function
  7812. * @param {?Object3D} [object3d=null] - The 3D object.
  7813. * @returns {Object3DNode<vec3>}
  7814. */
  7815. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7816. /**
  7817. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7818. *
  7819. * @tsl
  7820. * @function
  7821. * @param {?Object3D} [object3d=null] - The 3D object.
  7822. * @returns {Object3DNode<vec3>}
  7823. */
  7824. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7825. /**
  7826. * TSL function for creating an object 3D node that represents the object's radius.
  7827. *
  7828. * @tsl
  7829. * @function
  7830. * @param {?Object3D} [object3d=null] - The 3D object.
  7831. * @returns {Object3DNode<vec3>}
  7832. */
  7833. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS );
  7834. /**
  7835. * This type of node is a specialized version of `Object3DNode`
  7836. * with larger set of model related metrics. Unlike `Object3DNode`,
  7837. * `ModelNode` extracts the reference to the 3D object from the
  7838. * current node frame state.
  7839. *
  7840. * @augments Object3DNode
  7841. */
  7842. class ModelNode extends Object3DNode {
  7843. static get type() {
  7844. return 'ModelNode';
  7845. }
  7846. /**
  7847. * Constructs a new object model node.
  7848. *
  7849. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7850. */
  7851. constructor( scope ) {
  7852. super( scope );
  7853. }
  7854. /**
  7855. * Extracts the model reference from the frame state and then
  7856. * updates the uniform value depending on the scope.
  7857. *
  7858. * @param {NodeFrame} frame - The current node frame.
  7859. */
  7860. update( frame ) {
  7861. this.object3d = frame.object;
  7862. super.update( frame );
  7863. }
  7864. }
  7865. /**
  7866. * TSL object that represents the object's direction in world space.
  7867. *
  7868. * @tsl
  7869. * @type {ModelNode<vec3>}
  7870. */
  7871. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7872. /**
  7873. * TSL object that represents the object's world matrix.
  7874. *
  7875. * @tsl
  7876. * @type {ModelNode<mat4>}
  7877. */
  7878. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7879. /**
  7880. * TSL object that represents the object's position in world space.
  7881. *
  7882. * @tsl
  7883. * @type {ModelNode<vec3>}
  7884. */
  7885. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7886. /**
  7887. * TSL object that represents the object's scale in world space.
  7888. *
  7889. * @tsl
  7890. * @type {ModelNode<vec3>}
  7891. */
  7892. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7893. /**
  7894. * TSL object that represents the object's position in view/camera space.
  7895. *
  7896. * @tsl
  7897. * @type {ModelNode<vec3>}
  7898. */
  7899. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7900. /**
  7901. * TSL object that represents the object's radius.
  7902. *
  7903. * @tsl
  7904. * @type {ModelNode<float>}
  7905. */
  7906. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  7907. /**
  7908. * TSL object that represents the object's normal matrix.
  7909. *
  7910. * @tsl
  7911. * @type {UniformNode<mat3>}
  7912. */
  7913. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7914. /**
  7915. * TSL object that represents the object's inverse world matrix.
  7916. *
  7917. * @tsl
  7918. * @type {UniformNode<mat4>}
  7919. */
  7920. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7921. /**
  7922. * TSL object that represents the object's model view matrix.
  7923. *
  7924. * @tsl
  7925. * @type {Node<mat4>}
  7926. */
  7927. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7928. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7929. } ).once() )().toVar( 'modelViewMatrix' );
  7930. // GPU Precision
  7931. /**
  7932. * TSL object that represents the object's model view in `mediump` precision.
  7933. *
  7934. * @tsl
  7935. * @type {Node<mat4>}
  7936. */
  7937. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7938. // CPU Precision
  7939. /**
  7940. * TSL object that represents the object's model view in `highp` precision
  7941. * which is achieved by computing the matrix in JS and not in the shader.
  7942. *
  7943. * @tsl
  7944. * @type {Node<mat4>}
  7945. */
  7946. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7947. builder.context.isHighPrecisionModelViewMatrix = true;
  7948. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7949. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7950. } );
  7951. } ).once() )().toVar( 'highpModelViewMatrix' );
  7952. /**
  7953. * TSL object that represents the object's model normal view in `highp` precision
  7954. * which is achieved by computing the matrix in JS and not in the shader.
  7955. *
  7956. * @tsl
  7957. * @type {Node<mat3>}
  7958. */
  7959. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7960. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7961. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7962. if ( isHighPrecisionModelViewMatrix !== true ) {
  7963. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7964. }
  7965. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7966. } );
  7967. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7968. /**
  7969. * TSL object that represents the position attribute of the current rendered object.
  7970. *
  7971. * @tsl
  7972. * @type {AttributeNode<vec3>}
  7973. */
  7974. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7975. /**
  7976. * TSL object that represents the vertex position in local space of the current rendered object.
  7977. *
  7978. * @tsl
  7979. * @type {AttributeNode<vec3>}
  7980. */
  7981. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  7982. /**
  7983. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7984. * Used in context of {@link VelocityNode} for rendering motion vectors.
  7985. *
  7986. * @tsl
  7987. * @type {AttributeNode<vec3>}
  7988. */
  7989. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  7990. /**
  7991. * TSL object that represents the vertex position in world space of the current rendered object.
  7992. *
  7993. * @tsl
  7994. * @type {VaryingNode<vec3>}
  7995. */
  7996. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7997. /**
  7998. * TSL object that represents the position world direction of the current rendered object.
  7999. *
  8000. * @tsl
  8001. * @type {Node<vec3>}
  8002. */
  8003. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  8004. /**
  8005. * TSL object that represents the vertex position in view space of the current rendered object.
  8006. *
  8007. * @tsl
  8008. * @type {VaryingNode<vec3>}
  8009. */
  8010. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8011. return builder.context.setupPositionView();
  8012. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  8013. /**
  8014. * TSL object that represents the position view direction of the current rendered object.
  8015. *
  8016. * @tsl
  8017. * @type {VaryingNode<vec3>}
  8018. */
  8019. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8020. /**
  8021. * This node can be used to evaluate whether a primitive is front or back facing.
  8022. *
  8023. * @augments Node
  8024. */
  8025. class FrontFacingNode extends Node {
  8026. static get type() {
  8027. return 'FrontFacingNode';
  8028. }
  8029. /**
  8030. * Constructs a new front facing node.
  8031. */
  8032. constructor() {
  8033. super( 'bool' );
  8034. /**
  8035. * This flag can be used for type testing.
  8036. *
  8037. * @type {boolean}
  8038. * @readonly
  8039. * @default true
  8040. */
  8041. this.isFrontFacingNode = true;
  8042. }
  8043. generate( builder ) {
  8044. const { renderer, material } = builder;
  8045. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8046. if ( material.side === BackSide ) {
  8047. return 'false';
  8048. }
  8049. }
  8050. return builder.getFrontFacing();
  8051. }
  8052. }
  8053. /**
  8054. * TSL object that represents whether a primitive is front or back facing
  8055. *
  8056. * @tsl
  8057. * @type {FrontFacingNode<bool>}
  8058. */
  8059. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8060. /**
  8061. * TSL object that represents the front facing status as a number instead of a bool.
  8062. * `1` means front facing, `-1` means back facing.
  8063. *
  8064. * @tsl
  8065. * @type {Node<float>}
  8066. */
  8067. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8068. /**
  8069. * TSL object that represents the normal attribute of the current rendered object.
  8070. *
  8071. * @tsl
  8072. * @type {Node<vec3>}
  8073. */
  8074. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8075. /**
  8076. * TSL object that represents the vertex normal in local space of the current rendered object.
  8077. *
  8078. * @tsl
  8079. * @type {Node<vec3>}
  8080. */
  8081. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8082. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8083. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  8084. return vec3( 0, 1, 0 );
  8085. }
  8086. return normalGeometry;
  8087. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8088. /**
  8089. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  8090. *
  8091. * @tsl
  8092. * @type {Node<vec3>}
  8093. */
  8094. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8095. /**
  8096. * TSL object that represents the vertex normal in view space of the current rendered object.
  8097. *
  8098. * @tsl
  8099. * @type {Node<vec3>}
  8100. */
  8101. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8102. let node;
  8103. if ( builder.material.flatShading === true ) {
  8104. node = normalFlat;
  8105. } else {
  8106. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  8107. }
  8108. return node;
  8109. }, 'vec3' ).once() )().toVar( 'normalView' );
  8110. /**
  8111. * TSL object that represents the vertex normal in world space of the current rendered object.
  8112. *
  8113. * @tsl
  8114. * @type {Node<vec3>}
  8115. */
  8116. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  8117. /**
  8118. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  8119. *
  8120. * @tsl
  8121. * @type {Node<vec3>}
  8122. */
  8123. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8124. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8125. return builder.context.setupNormal().context( { getUV: null } );
  8126. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  8127. /**
  8128. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  8129. *
  8130. * @tsl
  8131. * @type {Node<vec3>}
  8132. */
  8133. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  8134. /**
  8135. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  8136. *
  8137. * @tsl
  8138. * @type {Node<vec3>}
  8139. */
  8140. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8141. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8142. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  8143. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  8144. /**
  8145. * Transforms the normal with the given matrix.
  8146. *
  8147. * @tsl
  8148. * @function
  8149. * @param {Node<vec3>} normal - The normal.
  8150. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8151. * @return {Node<vec3>} The transformed normal.
  8152. */
  8153. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8154. const m = mat3( matrix );
  8155. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8156. return m.mul( transformedNormal ).xyz;
  8157. } );
  8158. /**
  8159. * Transforms the given normal from local to view space.
  8160. *
  8161. * @tsl
  8162. * @function
  8163. * @param {Node<vec3>} normal - The normal.
  8164. * @param {NodeBuilder} builder - The current node builder.
  8165. * @return {Node<vec3>} The transformed normal.
  8166. */
  8167. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8168. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  8169. if ( modelNormalViewMatrix !== null ) {
  8170. return modelNormalViewMatrix.transformDirection( normal );
  8171. }
  8172. //
  8173. const transformedNormal = modelNormalMatrix.mul( normal );
  8174. return cameraViewMatrix.transformDirection( transformedNormal );
  8175. } );
  8176. const _e1$1 = /*@__PURE__*/ new Euler();
  8177. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8178. /**
  8179. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8180. *
  8181. * @tsl
  8182. * @type {UniformNode<float>}
  8183. */
  8184. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  8185. /**
  8186. * TSL object that represents the intensity of environment maps of PBR materials.
  8187. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  8188. *
  8189. * @tsl
  8190. * @type {Node<float>}
  8191. */
  8192. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  8193. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  8194. } );
  8195. /**
  8196. * TSL object that represents the rotation of environment maps.
  8197. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  8198. * rotation of `scene.environment` instead.
  8199. *
  8200. * @tsl
  8201. * @type {Node<mat4>}
  8202. */
  8203. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  8204. return frame.material;
  8205. } ).onObjectUpdate( function ( { material, scene } ) {
  8206. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  8207. if ( rotation ) {
  8208. _e1$1.copy( rotation );
  8209. _m1$1.makeRotationFromEuler( _e1$1 );
  8210. } else {
  8211. _m1$1.identity();
  8212. }
  8213. return _m1$1;
  8214. } );
  8215. /**
  8216. * The reflect vector in view space.
  8217. *
  8218. * @tsl
  8219. * @type {Node<vec3>}
  8220. */
  8221. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  8222. /**
  8223. * The refract vector in view space.
  8224. *
  8225. * @tsl
  8226. * @type {Node<vec3>}
  8227. */
  8228. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  8229. /**
  8230. * Used for sampling cube maps when using cube reflection mapping.
  8231. *
  8232. * @tsl
  8233. * @type {Node<vec3>}
  8234. */
  8235. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8236. /**
  8237. * Used for sampling cube maps when using cube refraction mapping.
  8238. *
  8239. * @tsl
  8240. * @type {Node<vec3>}
  8241. */
  8242. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8243. /**
  8244. * This type of uniform node represents a cube texture.
  8245. *
  8246. * @augments TextureNode
  8247. */
  8248. class CubeTextureNode extends TextureNode {
  8249. static get type() {
  8250. return 'CubeTextureNode';
  8251. }
  8252. /**
  8253. * Constructs a new cube texture node.
  8254. *
  8255. * @param {CubeTexture} value - The cube texture.
  8256. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8257. * @param {?Node<int>} [levelNode=null] - The level node.
  8258. * @param {?Node<float>} [biasNode=null] - The bias node.
  8259. */
  8260. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8261. super( value, uvNode, levelNode, biasNode );
  8262. /**
  8263. * This flag can be used for type testing.
  8264. *
  8265. * @type {boolean}
  8266. * @readonly
  8267. * @default true
  8268. */
  8269. this.isCubeTextureNode = true;
  8270. }
  8271. /**
  8272. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8273. *
  8274. * @param {NodeBuilder} builder - The current node builder.
  8275. * @return {string} The input type.
  8276. */
  8277. getInputType( /*builder*/ ) {
  8278. return 'cubeTexture';
  8279. }
  8280. /**
  8281. * Returns a default uvs based on the mapping type of the cube texture.
  8282. *
  8283. * @return {Node<vec3>} The default uv attribute.
  8284. */
  8285. getDefaultUV() {
  8286. const texture = this.value;
  8287. if ( texture.mapping === CubeReflectionMapping ) {
  8288. return reflectVector;
  8289. } else if ( texture.mapping === CubeRefractionMapping ) {
  8290. return refractVector;
  8291. } else {
  8292. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8293. return vec3( 0, 0, 0 );
  8294. }
  8295. }
  8296. /**
  8297. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8298. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8299. *
  8300. * @param {boolean} value - The update toggle.
  8301. */
  8302. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8303. /**
  8304. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8305. * to modify the uv node for correct sampling.
  8306. *
  8307. * @param {NodeBuilder} builder - The current node builder.
  8308. * @param {Node} uvNode - The uv node to setup.
  8309. * @return {Node} The updated uv node.
  8310. */
  8311. setupUV( builder, uvNode ) {
  8312. const texture = this.value;
  8313. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8314. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  8315. }
  8316. return materialEnvRotation.mul( uvNode );
  8317. }
  8318. /**
  8319. * Generates the uv code snippet.
  8320. *
  8321. * @param {NodeBuilder} builder - The current node builder.
  8322. * @param {Node} cubeUV - The uv node to generate code for.
  8323. * @return {string} The generated code snippet.
  8324. */
  8325. generateUV( builder, cubeUV ) {
  8326. return cubeUV.build( builder, 'vec3' );
  8327. }
  8328. }
  8329. /**
  8330. * TSL function for creating a cube texture node.
  8331. *
  8332. * @tsl
  8333. * @function
  8334. * @param {CubeTexture} value - The cube texture.
  8335. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8336. * @param {?Node<int>} [levelNode=null] - The level node.
  8337. * @param {?Node<float>} [biasNode=null] - The bias node.
  8338. * @returns {CubeTextureNode}
  8339. */
  8340. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  8341. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8342. /**
  8343. * This class is only relevant if the referenced property is array-like.
  8344. * In this case, `ReferenceElementNode` allows to refer to a specific
  8345. * element inside the data structure via an index.
  8346. *
  8347. * @augments ArrayElementNode
  8348. */
  8349. class ReferenceElementNode extends ArrayElementNode {
  8350. static get type() {
  8351. return 'ReferenceElementNode';
  8352. }
  8353. /**
  8354. * Constructs a new reference element node.
  8355. *
  8356. * @param {?ReferenceNode} referenceNode - The reference node.
  8357. * @param {Node} indexNode - The index node that defines the element access.
  8358. */
  8359. constructor( referenceNode, indexNode ) {
  8360. super( referenceNode, indexNode );
  8361. /**
  8362. * Similar to {@link ReferenceNode#reference}, an additional
  8363. * property references to the current node.
  8364. *
  8365. * @type {?ReferenceNode}
  8366. * @default null
  8367. */
  8368. this.referenceNode = referenceNode;
  8369. /**
  8370. * This flag can be used for type testing.
  8371. *
  8372. * @type {boolean}
  8373. * @readonly
  8374. * @default true
  8375. */
  8376. this.isReferenceElementNode = true;
  8377. }
  8378. /**
  8379. * This method is overwritten since the node type is inferred from
  8380. * the uniform type of the reference node.
  8381. *
  8382. * @return {string} The node type.
  8383. */
  8384. getNodeType() {
  8385. return this.referenceNode.uniformType;
  8386. }
  8387. generate( builder ) {
  8388. const snippet = super.generate( builder );
  8389. const arrayType = this.referenceNode.getNodeType();
  8390. const elementType = this.getNodeType();
  8391. return builder.format( snippet, arrayType, elementType );
  8392. }
  8393. }
  8394. /**
  8395. * This type of node establishes a reference to a property of another object.
  8396. * In this way, the value of the node is automatically linked to the value of
  8397. * referenced object. Reference nodes internally represent the linked value
  8398. * as a uniform.
  8399. *
  8400. * @augments Node
  8401. */
  8402. class ReferenceNode extends Node {
  8403. static get type() {
  8404. return 'ReferenceNode';
  8405. }
  8406. /**
  8407. * Constructs a new reference node.
  8408. *
  8409. * @param {string} property - The name of the property the node refers to.
  8410. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  8411. * @param {?Object} [object=null] - The object the property belongs to.
  8412. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8413. */
  8414. constructor( property, uniformType, object = null, count = null ) {
  8415. super();
  8416. /**
  8417. * The name of the property the node refers to.
  8418. *
  8419. * @type {string}
  8420. */
  8421. this.property = property;
  8422. /**
  8423. * The uniform type that should be used to represent the property value.
  8424. *
  8425. * @type {string}
  8426. */
  8427. this.uniformType = uniformType;
  8428. /**
  8429. * The object the property belongs to.
  8430. *
  8431. * @type {?Object}
  8432. * @default null
  8433. */
  8434. this.object = object;
  8435. /**
  8436. * When the linked property is an array, this parameter defines its length.
  8437. *
  8438. * @type {?number}
  8439. * @default null
  8440. */
  8441. this.count = count;
  8442. /**
  8443. * The property name might have dots so nested properties can be referred.
  8444. * The hierarchy of the names is stored inside this array.
  8445. *
  8446. * @type {Array<string>}
  8447. */
  8448. this.properties = property.split( '.' );
  8449. /**
  8450. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  8451. * since the final reference might be updated from calling code.
  8452. *
  8453. * @type {?Object}
  8454. * @default null
  8455. */
  8456. this.reference = object;
  8457. /**
  8458. * The uniform node that holds the value of the reference node.
  8459. *
  8460. * @type {UniformNode}
  8461. * @default null
  8462. */
  8463. this.node = null;
  8464. /**
  8465. * The uniform group of the internal uniform.
  8466. *
  8467. * @type {UniformGroupNode}
  8468. * @default null
  8469. */
  8470. this.group = null;
  8471. /**
  8472. * An optional label of the internal uniform node.
  8473. *
  8474. * @type {?string}
  8475. * @default null
  8476. */
  8477. this.name = null;
  8478. /**
  8479. * Overwritten since reference nodes are updated per object.
  8480. *
  8481. * @type {string}
  8482. * @default 'object'
  8483. */
  8484. this.updateType = NodeUpdateType.OBJECT;
  8485. }
  8486. /**
  8487. * When the referred property is array-like, this method can be used
  8488. * to access elements via an index node.
  8489. *
  8490. * @param {IndexNode} indexNode - indexNode.
  8491. * @return {ReferenceElementNode} A reference to an element.
  8492. */
  8493. element( indexNode ) {
  8494. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8495. }
  8496. /**
  8497. * Sets the uniform group for this reference node.
  8498. *
  8499. * @param {UniformGroupNode} group - The uniform group to set.
  8500. * @return {ReferenceNode} A reference to this node.
  8501. */
  8502. setGroup( group ) {
  8503. this.group = group;
  8504. return this;
  8505. }
  8506. /**
  8507. * Sets the label for the internal uniform.
  8508. *
  8509. * @param {string} name - The label to set.
  8510. * @return {ReferenceNode} A reference to this node.
  8511. */
  8512. label( name ) {
  8513. this.name = name;
  8514. return this;
  8515. }
  8516. /**
  8517. * Sets the node type which automatically defines the internal
  8518. * uniform type.
  8519. *
  8520. * @param {string} uniformType - The type to set.
  8521. */
  8522. setNodeType( uniformType ) {
  8523. let node = null;
  8524. if ( this.count !== null ) {
  8525. node = buffer( null, uniformType, this.count );
  8526. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8527. node = uniformArray( null, uniformType );
  8528. } else if ( uniformType === 'texture' ) {
  8529. node = texture( null );
  8530. } else if ( uniformType === 'cubeTexture' ) {
  8531. node = cubeTexture( null );
  8532. } else {
  8533. node = uniform( null, uniformType );
  8534. }
  8535. if ( this.group !== null ) {
  8536. node.setGroup( this.group );
  8537. }
  8538. if ( this.name !== null ) node.label( this.name );
  8539. this.node = node.getSelf();
  8540. }
  8541. /**
  8542. * This method is overwritten since the node type is inferred from
  8543. * the type of the reference node.
  8544. *
  8545. * @param {NodeBuilder} builder - The current node builder.
  8546. * @return {string} The node type.
  8547. */
  8548. getNodeType( builder ) {
  8549. if ( this.node === null ) {
  8550. this.updateReference( builder );
  8551. this.updateValue();
  8552. }
  8553. return this.node.getNodeType( builder );
  8554. }
  8555. /**
  8556. * Returns the property value from the given referred object.
  8557. *
  8558. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8559. * @return {any} The value.
  8560. */
  8561. getValueFromReference( object = this.reference ) {
  8562. const { properties } = this;
  8563. let value = object[ properties[ 0 ] ];
  8564. for ( let i = 1; i < properties.length; i ++ ) {
  8565. value = value[ properties[ i ] ];
  8566. }
  8567. return value;
  8568. }
  8569. /**
  8570. * Allows to update the reference based on the given state. The state is only
  8571. * evaluated {@link ReferenceNode#object} is not set.
  8572. *
  8573. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8574. * @return {Object} The updated reference.
  8575. */
  8576. updateReference( state ) {
  8577. this.reference = this.object !== null ? this.object : state.object;
  8578. return this.reference;
  8579. }
  8580. /**
  8581. * The output of the reference node is the internal uniform node.
  8582. *
  8583. * @param {NodeBuilder} builder - The current node builder.
  8584. * @return {UniformNode} The output node.
  8585. */
  8586. setup( /* builder */ ) {
  8587. this.updateValue();
  8588. return this.node;
  8589. }
  8590. /**
  8591. * Overwritten to to update the internal uniform value.
  8592. *
  8593. * @param {NodeFrame} frame - A reference to the current node frame.
  8594. */
  8595. update( /*frame*/ ) {
  8596. this.updateValue();
  8597. }
  8598. /**
  8599. * Retrieves the value from the referred object property and uses it
  8600. * to updated the internal uniform.
  8601. */
  8602. updateValue() {
  8603. if ( this.node === null ) this.setNodeType( this.uniformType );
  8604. const value = this.getValueFromReference();
  8605. if ( Array.isArray( value ) ) {
  8606. this.node.array = value;
  8607. } else {
  8608. this.node.value = value;
  8609. }
  8610. }
  8611. }
  8612. /**
  8613. * TSL function for creating a reference node.
  8614. *
  8615. * @tsl
  8616. * @function
  8617. * @param {string} name - The name of the property the node refers to.
  8618. * @param {string} type - The uniform type that should be used to represent the property value.
  8619. * @param {?Object} [object] - The object the property belongs to.
  8620. * @returns {ReferenceNode}
  8621. */
  8622. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8623. /**
  8624. * TSL function for creating a reference node. Use this function if you want need a reference
  8625. * to an array-like property that should be represented as a uniform buffer.
  8626. *
  8627. * @tsl
  8628. * @function
  8629. * @param {string} name - The name of the property the node refers to.
  8630. * @param {string} type - The uniform type that should be used to represent the property value.
  8631. * @param {number} count - The number of value inside the array-like object.
  8632. * @param {Object} object - An array-like object the property belongs to.
  8633. * @returns {ReferenceNode}
  8634. */
  8635. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8636. /**
  8637. * This node is a special type of reference node which is intended
  8638. * for linking material properties with node values.
  8639. * ```js
  8640. * const opacityNode = materialReference( 'opacity', 'float', material );
  8641. * ```
  8642. * When changing `material.opacity`, the node value of `opacityNode` will
  8643. * automatically be updated.
  8644. *
  8645. * @augments ReferenceNode
  8646. */
  8647. class MaterialReferenceNode extends ReferenceNode {
  8648. static get type() {
  8649. return 'MaterialReferenceNode';
  8650. }
  8651. /**
  8652. * Constructs a new material reference node.
  8653. *
  8654. * @param {string} property - The name of the property the node refers to.
  8655. * @param {string} inputType - The uniform type that should be used to represent the property value.
  8656. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  8657. * the node refers to the material of the current rendered object.
  8658. */
  8659. constructor( property, inputType, material = null ) {
  8660. super( property, inputType, material );
  8661. /**
  8662. * The material the property belongs to. When no material is set,
  8663. * the node refers to the material of the current rendered object.
  8664. *
  8665. * @type {?Material}
  8666. * @default null
  8667. */
  8668. this.material = material;
  8669. /**
  8670. * This flag can be used for type testing.
  8671. *
  8672. * @type {boolean}
  8673. * @readonly
  8674. * @default true
  8675. */
  8676. this.isMaterialReferenceNode = true;
  8677. }
  8678. /**
  8679. * Updates the reference based on the given state. The state is only evaluated
  8680. * {@link MaterialReferenceNode#material} is not set.
  8681. *
  8682. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8683. * @return {Object} The updated reference.
  8684. */
  8685. updateReference( state ) {
  8686. this.reference = this.material !== null ? this.material : state.material;
  8687. return this.reference;
  8688. }
  8689. }
  8690. /**
  8691. * TSL function for creating a material reference node.
  8692. *
  8693. * @tsl
  8694. * @function
  8695. * @param {string} name - The name of the property the node refers to.
  8696. * @param {string} type - The uniform type that should be used to represent the property value.
  8697. * @param {?Material} [material=null] - The material the property belongs to.
  8698. * When no material is set, the node refers to the material of the current rendered object.
  8699. * @returns {MaterialReferenceNode}
  8700. */
  8701. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8702. /**
  8703. * TSL object that represents the tangent attribute of the current rendered object.
  8704. *
  8705. * @tsl
  8706. * @type {Node<vec4>}
  8707. */
  8708. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8709. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8710. builder.geometry.computeTangents();
  8711. }
  8712. return attribute( 'tangent', 'vec4' );
  8713. } )();
  8714. /**
  8715. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8716. *
  8717. * @tsl
  8718. * @type {Node<vec3>}
  8719. */
  8720. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8721. /**
  8722. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8723. *
  8724. * @tsl
  8725. * @type {Node<vec3>}
  8726. */
  8727. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8728. /**
  8729. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8730. *
  8731. * @tsl
  8732. * @type {Node<vec3>}
  8733. */
  8734. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8735. /**
  8736. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8737. *
  8738. * @tsl
  8739. * @type {Node<vec3>}
  8740. */
  8741. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8742. /**
  8743. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8744. *
  8745. * @tsl
  8746. * @type {Node<vec3>}
  8747. */
  8748. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8749. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8750. /**
  8751. * TSL object that represents the bitangent attribute of the current rendered object.
  8752. *
  8753. * @tsl
  8754. * @type {Node<vec3>}
  8755. */
  8756. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8757. /**
  8758. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8759. *
  8760. * @tsl
  8761. * @type {Node<vec3>}
  8762. */
  8763. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8764. /**
  8765. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8766. *
  8767. * @tsl
  8768. * @type {Node<vec4>}
  8769. */
  8770. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8771. /**
  8772. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8773. *
  8774. * @tsl
  8775. * @type {Node<vec4>}
  8776. */
  8777. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8778. /**
  8779. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8780. *
  8781. * @tsl
  8782. * @type {Node<vec4>}
  8783. */
  8784. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8785. /**
  8786. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8787. *
  8788. * @tsl
  8789. * @type {Node<vec4>}
  8790. */
  8791. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8792. /**
  8793. * TSL object that represents the TBN matrix in view space.
  8794. *
  8795. * @tsl
  8796. * @type {Node<mat3>}
  8797. */
  8798. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8799. /**
  8800. * TSL object that represents the parallax direction.
  8801. *
  8802. * @tsl
  8803. * @type {Node<mat3>}
  8804. */
  8805. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8806. /**
  8807. * TSL function for computing parallax uv coordinates.
  8808. *
  8809. * @tsl
  8810. * @function
  8811. * @param {Node<vec2>} uv - A uv node.
  8812. * @param {Node<vec2>} scale - A scale node.
  8813. * @returns {Node<vec2>} Parallax uv coordinates.
  8814. */
  8815. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8816. /**
  8817. * TSL function for computing bent normals.
  8818. *
  8819. * @tsl
  8820. * @function
  8821. * @returns {Node<vec3>} Bent normals.
  8822. */
  8823. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8824. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8825. let bentNormal = anisotropyB.cross( positionViewDirection );
  8826. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8827. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8828. return bentNormal;
  8829. } )();
  8830. // Normal Mapping Without Precomputed Tangents
  8831. // http://www.thetenthplanet.de/archives/1180
  8832. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8833. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8834. const q0 = eye_pos.dFdx();
  8835. const q1 = eye_pos.dFdy();
  8836. const st0 = uv.dFdx();
  8837. const st1 = uv.dFdy();
  8838. const N = surf_norm; // normalized
  8839. const q1perp = q1.cross( N );
  8840. const q0perp = N.cross( q0 );
  8841. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8842. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8843. const det = T.dot( T ).max( B.dot( B ) );
  8844. const scale = faceDirection.mul( det.inverseSqrt() );
  8845. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8846. } );
  8847. /**
  8848. * This class can be used for applying normals maps to materials.
  8849. *
  8850. * ```js
  8851. * material.normalNode = normalMap( texture( normalTex ) );
  8852. * ```
  8853. *
  8854. * @augments TempNode
  8855. */
  8856. class NormalMapNode extends TempNode {
  8857. static get type() {
  8858. return 'NormalMapNode';
  8859. }
  8860. /**
  8861. * Constructs a new normal map node.
  8862. *
  8863. * @param {Node<vec3>} node - Represents the normal map data.
  8864. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  8865. */
  8866. constructor( node, scaleNode = null ) {
  8867. super( 'vec3' );
  8868. /**
  8869. * Represents the normal map data.
  8870. *
  8871. * @type {Node<vec3>}
  8872. */
  8873. this.node = node;
  8874. /**
  8875. * Controls the intensity of the effect.
  8876. *
  8877. * @type {?Node<vec2>}
  8878. * @default null
  8879. */
  8880. this.scaleNode = scaleNode;
  8881. /**
  8882. * The normal map type.
  8883. *
  8884. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8885. * @default TangentSpaceNormalMap
  8886. */
  8887. this.normalMapType = TangentSpaceNormalMap;
  8888. }
  8889. setup( builder ) {
  8890. const { normalMapType, scaleNode } = this;
  8891. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8892. if ( scaleNode !== null ) {
  8893. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8894. }
  8895. let outputNode = null;
  8896. if ( normalMapType === ObjectSpaceNormalMap ) {
  8897. outputNode = transformNormalToView( normalMap );
  8898. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8899. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8900. if ( tangent === true ) {
  8901. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8902. } else {
  8903. outputNode = perturbNormal2Arb( {
  8904. eye_pos: positionView,
  8905. surf_norm: normalView,
  8906. mapN: normalMap,
  8907. uv: uv()
  8908. } );
  8909. }
  8910. }
  8911. return outputNode;
  8912. }
  8913. }
  8914. /**
  8915. * TSL function for creating a normal map node.
  8916. *
  8917. * @tsl
  8918. * @function
  8919. * @param {Node<vec3>} node - Represents the normal map data.
  8920. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  8921. * @returns {NormalMapNode}
  8922. */
  8923. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8924. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8925. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8926. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8927. // It's used to preserve the same TextureNode instance
  8928. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8929. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8930. return vec2(
  8931. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8932. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8933. ).mul( bumpScale );
  8934. } );
  8935. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8936. const perturbNormalArb = Fn( ( inputs ) => {
  8937. const { surf_pos, surf_norm, dHdxy } = inputs;
  8938. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8939. const vSigmaX = surf_pos.dFdx().normalize();
  8940. const vSigmaY = surf_pos.dFdy().normalize();
  8941. const vN = surf_norm; // normalized
  8942. const R1 = vSigmaY.cross( vN );
  8943. const R2 = vN.cross( vSigmaX );
  8944. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8945. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8946. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8947. } );
  8948. /**
  8949. * This class can be used for applying bump maps to materials.
  8950. *
  8951. * ```js
  8952. * material.normalNode = bumpMap( texture( bumpTex ) );
  8953. * ```
  8954. *
  8955. * @augments TempNode
  8956. */
  8957. class BumpMapNode extends TempNode {
  8958. static get type() {
  8959. return 'BumpMapNode';
  8960. }
  8961. /**
  8962. * Constructs a new bump map node.
  8963. *
  8964. * @param {Node<float>} textureNode - Represents the bump map data.
  8965. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  8966. */
  8967. constructor( textureNode, scaleNode = null ) {
  8968. super( 'vec3' );
  8969. /**
  8970. * Represents the bump map data.
  8971. *
  8972. * @type {Node<float>}
  8973. */
  8974. this.textureNode = textureNode;
  8975. /**
  8976. * Controls the intensity of the bump effect.
  8977. *
  8978. * @type {?Node<float>}
  8979. * @default null
  8980. */
  8981. this.scaleNode = scaleNode;
  8982. }
  8983. setup() {
  8984. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8985. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8986. return perturbNormalArb( {
  8987. surf_pos: positionView,
  8988. surf_norm: normalView,
  8989. dHdxy
  8990. } );
  8991. }
  8992. }
  8993. /**
  8994. * TSL function for creating a bump map node.
  8995. *
  8996. * @tsl
  8997. * @function
  8998. * @param {Node<float>} textureNode - Represents the bump map data.
  8999. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9000. * @returns {BumpMapNode}
  9001. */
  9002. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  9003. const _propertyCache = new Map();
  9004. /**
  9005. * This class should simplify the node access to material properties.
  9006. * It internal uses reference nodes to make sure changes to material
  9007. * properties are automatically reflected to predefined TSL objects
  9008. * like e.g. `materialColor`.
  9009. *
  9010. * @augments Node
  9011. */
  9012. class MaterialNode extends Node {
  9013. static get type() {
  9014. return 'MaterialNode';
  9015. }
  9016. /**
  9017. * Constructs a new material node.
  9018. *
  9019. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  9020. */
  9021. constructor( scope ) {
  9022. super();
  9023. /**
  9024. * The scope defines what material property is referred by the node.
  9025. *
  9026. * @type {string}
  9027. */
  9028. this.scope = scope;
  9029. }
  9030. /**
  9031. * Returns a cached reference node for the given property and type.
  9032. *
  9033. * @param {string} property - The name of the material property.
  9034. * @param {string} type - The uniform type of the property.
  9035. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9036. */
  9037. getCache( property, type ) {
  9038. let node = _propertyCache.get( property );
  9039. if ( node === undefined ) {
  9040. node = materialReference( property, type );
  9041. _propertyCache.set( property, node );
  9042. }
  9043. return node;
  9044. }
  9045. /**
  9046. * Returns a float-typed material reference node for the given property name.
  9047. *
  9048. * @param {string} property - The name of the material property.
  9049. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  9050. */
  9051. getFloat( property ) {
  9052. return this.getCache( property, 'float' );
  9053. }
  9054. /**
  9055. * Returns a color-typed material reference node for the given property name.
  9056. *
  9057. * @param {string} property - The name of the material property.
  9058. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  9059. */
  9060. getColor( property ) {
  9061. return this.getCache( property, 'color' );
  9062. }
  9063. /**
  9064. * Returns a texture-typed material reference node for the given property name.
  9065. *
  9066. * @param {string} property - The name of the material property.
  9067. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9068. */
  9069. getTexture( property ) {
  9070. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  9071. }
  9072. /**
  9073. * The node setup is done depending on the selected scope. Multiple material properties
  9074. * might be grouped into a single node composition if they logically belong together.
  9075. *
  9076. * @param {NodeBuilder} builder - The current node builder.
  9077. * @return {Node} The node representing the selected scope.
  9078. */
  9079. setup( builder ) {
  9080. const material = builder.context.material;
  9081. const scope = this.scope;
  9082. let node = null;
  9083. if ( scope === MaterialNode.COLOR ) {
  9084. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  9085. if ( material.map && material.map.isTexture === true ) {
  9086. node = colorNode.mul( this.getTexture( 'map' ) );
  9087. } else {
  9088. node = colorNode;
  9089. }
  9090. } else if ( scope === MaterialNode.OPACITY ) {
  9091. const opacityNode = this.getFloat( scope );
  9092. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9093. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9094. } else {
  9095. node = opacityNode;
  9096. }
  9097. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9098. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9099. node = this.getTexture( 'specular' ).r;
  9100. } else {
  9101. node = float( 1 );
  9102. }
  9103. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9104. const specularIntensityNode = this.getFloat( scope );
  9105. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9106. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9107. } else {
  9108. node = specularIntensityNode;
  9109. }
  9110. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9111. const specularColorNode = this.getColor( scope );
  9112. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9113. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9114. } else {
  9115. node = specularColorNode;
  9116. }
  9117. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9118. const roughnessNode = this.getFloat( scope );
  9119. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9120. node = roughnessNode.mul( this.getTexture( scope ).g );
  9121. } else {
  9122. node = roughnessNode;
  9123. }
  9124. } else if ( scope === MaterialNode.METALNESS ) {
  9125. const metalnessNode = this.getFloat( scope );
  9126. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9127. node = metalnessNode.mul( this.getTexture( scope ).b );
  9128. } else {
  9129. node = metalnessNode;
  9130. }
  9131. } else if ( scope === MaterialNode.EMISSIVE ) {
  9132. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9133. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9134. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9135. node = emissiveNode.mul( this.getTexture( scope ) );
  9136. } else {
  9137. node = emissiveNode;
  9138. }
  9139. } else if ( scope === MaterialNode.NORMAL ) {
  9140. if ( material.normalMap ) {
  9141. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9142. node.normalMapType = material.normalMapType;
  9143. } else if ( material.bumpMap ) {
  9144. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9145. } else {
  9146. node = normalView;
  9147. }
  9148. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9149. const clearcoatNode = this.getFloat( scope );
  9150. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9151. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9152. } else {
  9153. node = clearcoatNode;
  9154. }
  9155. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9156. const clearcoatRoughnessNode = this.getFloat( scope );
  9157. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9158. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9159. } else {
  9160. node = clearcoatRoughnessNode;
  9161. }
  9162. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9163. if ( material.clearcoatNormalMap ) {
  9164. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9165. } else {
  9166. node = normalView;
  9167. }
  9168. } else if ( scope === MaterialNode.SHEEN ) {
  9169. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9170. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9171. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9172. } else {
  9173. node = sheenNode;
  9174. }
  9175. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9176. const sheenRoughnessNode = this.getFloat( scope );
  9177. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9178. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9179. } else {
  9180. node = sheenRoughnessNode;
  9181. }
  9182. node = node.clamp( 0.07, 1.0 );
  9183. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9184. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9185. const anisotropyPolar = this.getTexture( scope );
  9186. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9187. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9188. } else {
  9189. node = materialAnisotropyVector;
  9190. }
  9191. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9192. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9193. if ( material.iridescenceThicknessMap ) {
  9194. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9195. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9196. } else {
  9197. node = iridescenceThicknessMaximum;
  9198. }
  9199. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9200. const transmissionNode = this.getFloat( scope );
  9201. if ( material.transmissionMap ) {
  9202. node = transmissionNode.mul( this.getTexture( scope ).r );
  9203. } else {
  9204. node = transmissionNode;
  9205. }
  9206. } else if ( scope === MaterialNode.THICKNESS ) {
  9207. const thicknessNode = this.getFloat( scope );
  9208. if ( material.thicknessMap ) {
  9209. node = thicknessNode.mul( this.getTexture( scope ).g );
  9210. } else {
  9211. node = thicknessNode;
  9212. }
  9213. } else if ( scope === MaterialNode.IOR ) {
  9214. node = this.getFloat( scope );
  9215. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9216. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9217. } else if ( scope === MaterialNode.AO ) {
  9218. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9219. } else {
  9220. const outputType = this.getNodeType( builder );
  9221. node = this.getCache( scope, outputType );
  9222. }
  9223. return node;
  9224. }
  9225. }
  9226. MaterialNode.ALPHA_TEST = 'alphaTest';
  9227. MaterialNode.COLOR = 'color';
  9228. MaterialNode.OPACITY = 'opacity';
  9229. MaterialNode.SHININESS = 'shininess';
  9230. MaterialNode.SPECULAR = 'specular';
  9231. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  9232. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  9233. MaterialNode.SPECULAR_COLOR = 'specularColor';
  9234. MaterialNode.REFLECTIVITY = 'reflectivity';
  9235. MaterialNode.ROUGHNESS = 'roughness';
  9236. MaterialNode.METALNESS = 'metalness';
  9237. MaterialNode.NORMAL = 'normal';
  9238. MaterialNode.CLEARCOAT = 'clearcoat';
  9239. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  9240. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  9241. MaterialNode.EMISSIVE = 'emissive';
  9242. MaterialNode.ROTATION = 'rotation';
  9243. MaterialNode.SHEEN = 'sheen';
  9244. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  9245. MaterialNode.ANISOTROPY = 'anisotropy';
  9246. MaterialNode.IRIDESCENCE = 'iridescence';
  9247. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  9248. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  9249. MaterialNode.IOR = 'ior';
  9250. MaterialNode.TRANSMISSION = 'transmission';
  9251. MaterialNode.THICKNESS = 'thickness';
  9252. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  9253. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  9254. MaterialNode.LINE_SCALE = 'scale';
  9255. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  9256. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  9257. MaterialNode.LINE_WIDTH = 'linewidth';
  9258. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  9259. MaterialNode.POINT_SIZE = 'size';
  9260. MaterialNode.DISPERSION = 'dispersion';
  9261. MaterialNode.LIGHT_MAP = 'light';
  9262. MaterialNode.AO = 'ao';
  9263. /**
  9264. * TSL object that represents alpha test of the current material.
  9265. *
  9266. * @tsl
  9267. * @type {Node<float>}
  9268. */
  9269. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  9270. /**
  9271. * TSL object that represents the diffuse color of the current material.
  9272. * The value is composed via `color` * `map`.
  9273. *
  9274. * @tsl
  9275. * @type {Node<vec3>}
  9276. */
  9277. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  9278. /**
  9279. * TSL object that represents the shininess of the current material.
  9280. *
  9281. * @tsl
  9282. * @type {Node<float>}
  9283. */
  9284. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9285. /**
  9286. * TSL object that represents the emissive color of the current material.
  9287. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9288. *
  9289. * @tsl
  9290. * @type {Node<vec3>}
  9291. */
  9292. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9293. /**
  9294. * TSL object that represents the opacity of the current material.
  9295. * The value is composed via `opacity` * `alphaMap`.
  9296. *
  9297. * @tsl
  9298. * @type {Node<float>}
  9299. */
  9300. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9301. /**
  9302. * TSL object that represents the specular of the current material.
  9303. *
  9304. * @tsl
  9305. * @type {Node<vec3>}
  9306. */
  9307. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9308. /**
  9309. * TSL object that represents the specular intensity of the current material.
  9310. * The value is composed via `specularIntensity` * `specularMap.a`.
  9311. *
  9312. * @tsl
  9313. * @type {Node<float>}
  9314. */
  9315. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9316. /**
  9317. * TSL object that represents the specular color of the current material.
  9318. * The value is composed via `specularColor` * `specularMap.rgb`.
  9319. *
  9320. * @tsl
  9321. * @type {Node<vec3>}
  9322. */
  9323. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9324. /**
  9325. * TSL object that represents the specular strength of the current material.
  9326. * The value is composed via `specularMap.r`.
  9327. *
  9328. * @tsl
  9329. * @type {Node<float>}
  9330. */
  9331. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9332. /**
  9333. * TSL object that represents the reflectivity of the current material.
  9334. *
  9335. * @tsl
  9336. * @type {Node<float>}
  9337. */
  9338. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9339. /**
  9340. * TSL object that represents the roughness of the current material.
  9341. * The value is composed via `roughness` * `roughnessMap.g`.
  9342. *
  9343. * @tsl
  9344. * @type {Node<float>}
  9345. */
  9346. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9347. /**
  9348. * TSL object that represents the metalness of the current material.
  9349. * The value is composed via `metalness` * `metalnessMap.b`.
  9350. *
  9351. * @tsl
  9352. * @type {Node<float>}
  9353. */
  9354. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9355. /**
  9356. * TSL object that represents the normal of the current material.
  9357. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9358. *
  9359. * @tsl
  9360. * @type {Node<vec3>}
  9361. */
  9362. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9363. /**
  9364. * TSL object that represents the clearcoat of the current material.
  9365. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9366. *
  9367. * @tsl
  9368. * @type {Node<float>}
  9369. */
  9370. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9371. /**
  9372. * TSL object that represents the clearcoat roughness of the current material.
  9373. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9374. *
  9375. * @tsl
  9376. * @type {Node<float>}
  9377. */
  9378. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9379. /**
  9380. * TSL object that represents the clearcoat normal of the current material.
  9381. * The value will be either `clearcoatNormalMap` or `normalView`.
  9382. *
  9383. * @tsl
  9384. * @type {Node<vec3>}
  9385. */
  9386. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9387. /**
  9388. * TSL object that represents the rotation of the current sprite material.
  9389. *
  9390. * @tsl
  9391. * @type {Node<float>}
  9392. */
  9393. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9394. /**
  9395. * TSL object that represents the sheen color of the current material.
  9396. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9397. *
  9398. * @tsl
  9399. * @type {Node<vec3>}
  9400. */
  9401. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9402. /**
  9403. * TSL object that represents the sheen roughness of the current material.
  9404. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9405. *
  9406. * @tsl
  9407. * @type {Node<float>}
  9408. */
  9409. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9410. /**
  9411. * TSL object that represents the anisotropy of the current material.
  9412. *
  9413. * @tsl
  9414. * @type {Node<vec2>}
  9415. */
  9416. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9417. /**
  9418. * TSL object that represents the iridescence of the current material.
  9419. *
  9420. * @tsl
  9421. * @type {Node<float>}
  9422. */
  9423. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9424. /**
  9425. * TSL object that represents the iridescence IOR of the current material.
  9426. *
  9427. * @tsl
  9428. * @type {Node<float>}
  9429. */
  9430. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9431. /**
  9432. * TSL object that represents the iridescence thickness of the current material.
  9433. *
  9434. * @tsl
  9435. * @type {Node<float>}
  9436. */
  9437. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9438. /**
  9439. * TSL object that represents the transmission of the current material.
  9440. * The value is composed via `transmission` * `transmissionMap.r`.
  9441. *
  9442. * @tsl
  9443. * @type {Node<float>}
  9444. */
  9445. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9446. /**
  9447. * TSL object that represents the thickness of the current material.
  9448. * The value is composed via `thickness` * `thicknessMap.g`.
  9449. *
  9450. * @tsl
  9451. * @type {Node<float>}
  9452. */
  9453. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9454. /**
  9455. * TSL object that represents the IOR of the current material.
  9456. *
  9457. * @tsl
  9458. * @type {Node<float>}
  9459. */
  9460. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  9461. /**
  9462. * TSL object that represents the attenuation distance of the current material.
  9463. *
  9464. * @tsl
  9465. * @type {Node<float>}
  9466. */
  9467. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  9468. /**
  9469. * TSL object that represents the attenuation color of the current material.
  9470. *
  9471. * @tsl
  9472. * @type {Node<vec3>}
  9473. */
  9474. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  9475. /**
  9476. * TSL object that represents the scale of the current dashed line material.
  9477. *
  9478. * @tsl
  9479. * @type {Node<float>}
  9480. */
  9481. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  9482. /**
  9483. * TSL object that represents the dash size of the current dashed line material.
  9484. *
  9485. * @tsl
  9486. * @type {Node<float>}
  9487. */
  9488. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  9489. /**
  9490. * TSL object that represents the gap size of the current dashed line material.
  9491. *
  9492. * @tsl
  9493. * @type {Node<float>}
  9494. */
  9495. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  9496. /**
  9497. * TSL object that represents the line width of the current line material.
  9498. *
  9499. * @tsl
  9500. * @type {Node<float>}
  9501. */
  9502. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  9503. /**
  9504. * TSL object that represents the dash offset of the current line material.
  9505. *
  9506. * @tsl
  9507. * @type {Node<float>}
  9508. */
  9509. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  9510. /**
  9511. * TSL object that represents the point size of the current points material.
  9512. *
  9513. * @tsl
  9514. * @type {Node<float>}
  9515. */
  9516. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9517. /**
  9518. * TSL object that represents the dispersion of the current material.
  9519. *
  9520. * @tsl
  9521. * @type {Node<float>}
  9522. */
  9523. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9524. /**
  9525. * TSL object that represents the light map of the current material.
  9526. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9527. *
  9528. * @tsl
  9529. * @type {Node<vec3>}
  9530. */
  9531. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9532. /**
  9533. * TSL object that represents the ambient occlusion map of the current material.
  9534. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9535. *
  9536. * @tsl
  9537. * @type {Node<float>}
  9538. */
  9539. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9540. /**
  9541. * TSL object that represents the anisotropy vector of the current material.
  9542. *
  9543. * @tsl
  9544. * @type {Node<vec2>}
  9545. */
  9546. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9547. return frame.material;
  9548. } ).onRenderUpdate( function ( { material } ) {
  9549. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9550. } );
  9551. /**
  9552. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9553. *
  9554. * @tsl
  9555. * @type {VaryingNode<vec4>}
  9556. */
  9557. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9558. return builder.context.setupModelViewProjection();
  9559. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  9560. /**
  9561. * This class represents shader indices of different types. The following predefined node
  9562. * objects cover frequent use cases:
  9563. *
  9564. * - `vertexIndex`: The index of a vertex within a mesh.
  9565. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9566. * - `drawIndex`: The index of a draw call.
  9567. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9568. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9569. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9570. *
  9571. * @augments Node
  9572. */
  9573. class IndexNode extends Node {
  9574. static get type() {
  9575. return 'IndexNode';
  9576. }
  9577. /**
  9578. * Constructs a new index node.
  9579. *
  9580. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9581. */
  9582. constructor( scope ) {
  9583. super( 'uint' );
  9584. /**
  9585. * The scope of the index node.
  9586. *
  9587. * @type {string}
  9588. */
  9589. this.scope = scope;
  9590. /**
  9591. * This flag can be used for type testing.
  9592. *
  9593. * @type {boolean}
  9594. * @readonly
  9595. * @default true
  9596. */
  9597. this.isIndexNode = true;
  9598. }
  9599. generate( builder ) {
  9600. const nodeType = this.getNodeType( builder );
  9601. const scope = this.scope;
  9602. let propertyName;
  9603. if ( scope === IndexNode.VERTEX ) {
  9604. propertyName = builder.getVertexIndex();
  9605. } else if ( scope === IndexNode.INSTANCE ) {
  9606. propertyName = builder.getInstanceIndex();
  9607. } else if ( scope === IndexNode.DRAW ) {
  9608. propertyName = builder.getDrawIndex();
  9609. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9610. propertyName = builder.getInvocationLocalIndex();
  9611. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9612. propertyName = builder.getInvocationSubgroupIndex();
  9613. } else if ( scope === IndexNode.SUBGROUP ) {
  9614. propertyName = builder.getSubgroupIndex();
  9615. } else {
  9616. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9617. }
  9618. let output;
  9619. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9620. output = propertyName;
  9621. } else {
  9622. const nodeVarying = varying( this );
  9623. output = nodeVarying.build( builder, nodeType );
  9624. }
  9625. return output;
  9626. }
  9627. }
  9628. IndexNode.VERTEX = 'vertex';
  9629. IndexNode.INSTANCE = 'instance';
  9630. IndexNode.SUBGROUP = 'subgroup';
  9631. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9632. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9633. IndexNode.DRAW = 'draw';
  9634. /**
  9635. * TSL object that represents the index of a vertex within a mesh.
  9636. *
  9637. * @tsl
  9638. * @type {IndexNode}
  9639. */
  9640. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9641. /**
  9642. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9643. *
  9644. * @tsl
  9645. * @type {IndexNode}
  9646. */
  9647. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9648. /**
  9649. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9650. *
  9651. * @tsl
  9652. * @type {IndexNode}
  9653. */
  9654. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9655. /**
  9656. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9657. *
  9658. * @tsl
  9659. * @type {IndexNode}
  9660. */
  9661. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9662. /**
  9663. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9664. *
  9665. * @tsl
  9666. * @type {IndexNode}
  9667. */
  9668. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9669. /**
  9670. * TSL object that represents the index of a draw call.
  9671. *
  9672. * @tsl
  9673. * @type {IndexNode}
  9674. */
  9675. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9676. /**
  9677. * This node implements the vertex shader logic which is required
  9678. * when rendering 3D objects via instancing. The code makes sure
  9679. * vertex positions, normals and colors can be modified via instanced
  9680. * data.
  9681. *
  9682. * @augments Node
  9683. */
  9684. class InstanceNode extends Node {
  9685. static get type() {
  9686. return 'InstanceNode';
  9687. }
  9688. /**
  9689. * Constructs a new instance node.
  9690. *
  9691. * @param {number} count - The number of instances.
  9692. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9693. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9694. */
  9695. constructor( count, instanceMatrix, instanceColor ) {
  9696. super( 'void' );
  9697. /**
  9698. * The number of instances.
  9699. *
  9700. * @type {number}
  9701. */
  9702. this.count = count;
  9703. /**
  9704. * Instanced buffer attribute representing the transformation of instances.
  9705. *
  9706. * @type {InstancedBufferAttribute}
  9707. */
  9708. this.instanceMatrix = instanceMatrix;
  9709. /**
  9710. * Instanced buffer attribute representing the color of instances.
  9711. *
  9712. * @type {InstancedBufferAttribute}
  9713. */
  9714. this.instanceColor = instanceColor;
  9715. /**
  9716. * The node that represents the instance matrix data.
  9717. *
  9718. * @type {?Node}
  9719. */
  9720. this.instanceMatrixNode = null;
  9721. /**
  9722. * The node that represents the instance color data.
  9723. *
  9724. * @type {?Node}
  9725. */
  9726. this.instanceColorNode = null;
  9727. /**
  9728. * The update type is set to `frame` since an update
  9729. * of instanced buffer data must be checked per frame.
  9730. *
  9731. * @type {string}
  9732. * @default 'frame'
  9733. */
  9734. this.updateType = NodeUpdateType.FRAME;
  9735. /**
  9736. * A reference to a buffer that is used by `instanceMatrixNode`.
  9737. *
  9738. * @type {?InstancedInterleavedBuffer}
  9739. */
  9740. this.buffer = null;
  9741. /**
  9742. * A reference to a buffer that is used by `instanceColorNode`.
  9743. *
  9744. * @type {?InstancedBufferAttribute}
  9745. */
  9746. this.bufferColor = null;
  9747. }
  9748. /**
  9749. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9750. * to predefined node variables for accumulation. That follows the same patterns
  9751. * like with morph and skinning nodes.
  9752. *
  9753. * @param {NodeBuilder} builder - The current node builder.
  9754. */
  9755. setup( builder ) {
  9756. const { count, instanceMatrix, instanceColor } = this;
  9757. let { instanceMatrixNode, instanceColorNode } = this;
  9758. if ( instanceMatrixNode === null ) {
  9759. // 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.
  9760. if ( count <= 1000 ) {
  9761. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9762. } else {
  9763. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9764. this.buffer = buffer;
  9765. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9766. const instanceBuffers = [
  9767. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9768. bufferFn( buffer, 'vec4', 16, 0 ),
  9769. bufferFn( buffer, 'vec4', 16, 4 ),
  9770. bufferFn( buffer, 'vec4', 16, 8 ),
  9771. bufferFn( buffer, 'vec4', 16, 12 )
  9772. ];
  9773. instanceMatrixNode = mat4( ...instanceBuffers );
  9774. }
  9775. this.instanceMatrixNode = instanceMatrixNode;
  9776. }
  9777. if ( instanceColor && instanceColorNode === null ) {
  9778. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9779. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9780. this.bufferColor = buffer;
  9781. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9782. this.instanceColorNode = instanceColorNode;
  9783. }
  9784. // POSITION
  9785. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9786. positionLocal.assign( instancePosition );
  9787. // NORMAL
  9788. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9789. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9790. // ASSIGNS
  9791. normalLocal.assign( instanceNormal );
  9792. }
  9793. // COLOR
  9794. if ( this.instanceColorNode !== null ) {
  9795. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9796. }
  9797. }
  9798. /**
  9799. * Checks if the internal buffers required an update.
  9800. *
  9801. * @param {NodeFrame} frame - The current node frame.
  9802. */
  9803. update( /*frame*/ ) {
  9804. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9805. this.buffer.version = this.instanceMatrix.version;
  9806. }
  9807. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9808. this.bufferColor.version = this.instanceColor.version;
  9809. }
  9810. }
  9811. }
  9812. /**
  9813. * TSL function for creating an instance node.
  9814. *
  9815. * @tsl
  9816. * @function
  9817. * @param {number} count - The number of instances.
  9818. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9819. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9820. * @returns {InstanceNode}
  9821. */
  9822. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9823. /**
  9824. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9825. * It allows an easier setup of the instance node.
  9826. *
  9827. * @augments InstanceNode
  9828. */
  9829. class InstancedMeshNode extends InstanceNode {
  9830. static get type() {
  9831. return 'InstancedMeshNode';
  9832. }
  9833. /**
  9834. * Constructs a new instanced mesh node.
  9835. *
  9836. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9837. */
  9838. constructor( instancedMesh ) {
  9839. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9840. super( count, instanceMatrix, instanceColor );
  9841. /**
  9842. * A reference to the instanced mesh.
  9843. *
  9844. * @type {InstancedMesh}
  9845. */
  9846. this.instancedMesh = instancedMesh;
  9847. }
  9848. }
  9849. /**
  9850. * TSL function for creating an instanced mesh node.
  9851. *
  9852. * @tsl
  9853. * @function
  9854. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9855. * @returns {InstancedMeshNode}
  9856. */
  9857. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9858. /**
  9859. * This node implements the vertex shader logic which is required
  9860. * when rendering 3D objects via batching. `BatchNode` must be used
  9861. * with instances of {@link BatchedMesh}.
  9862. *
  9863. * @augments Node
  9864. */
  9865. class BatchNode extends Node {
  9866. static get type() {
  9867. return 'BatchNode';
  9868. }
  9869. /**
  9870. * Constructs a new batch node.
  9871. *
  9872. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9873. */
  9874. constructor( batchMesh ) {
  9875. super( 'void' );
  9876. /**
  9877. * A reference to batched mesh.
  9878. *
  9879. * @type {BatchedMesh}
  9880. */
  9881. this.batchMesh = batchMesh;
  9882. /**
  9883. * The batching index node.
  9884. *
  9885. * @type {?IndexNode}
  9886. * @default null
  9887. */
  9888. this.batchingIdNode = null;
  9889. }
  9890. /**
  9891. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9892. * to predefined node variables for accumulation. That follows the same patterns
  9893. * like with morph and skinning nodes.
  9894. *
  9895. * @param {NodeBuilder} builder - The current node builder.
  9896. */
  9897. setup( builder ) {
  9898. if ( this.batchingIdNode === null ) {
  9899. if ( builder.getDrawIndex() === null ) {
  9900. this.batchingIdNode = instanceIndex;
  9901. } else {
  9902. this.batchingIdNode = drawIndex;
  9903. }
  9904. }
  9905. const getIndirectIndex = Fn( ( [ id ] ) => {
  9906. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ) );
  9907. const x = int( id ).modInt( size );
  9908. const y = int( id ).div( size );
  9909. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9910. } ).setLayout( {
  9911. name: 'getIndirectIndex',
  9912. type: 'uint',
  9913. inputs: [
  9914. { name: 'id', type: 'int' }
  9915. ]
  9916. } );
  9917. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9918. const matricesTexture = this.batchMesh._matricesTexture;
  9919. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9920. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9921. const x = j.modInt( size );
  9922. const y = j.div( int( size ) );
  9923. const batchingMatrix = mat4(
  9924. textureLoad( matricesTexture, ivec2( x, y ) ),
  9925. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9926. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9927. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9928. );
  9929. const colorsTexture = this.batchMesh._colorsTexture;
  9930. if ( colorsTexture !== null ) {
  9931. const getBatchingColor = Fn( ( [ id ] ) => {
  9932. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9933. const j = id;
  9934. const x = j.modInt( size );
  9935. const y = j.div( size );
  9936. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9937. } ).setLayout( {
  9938. name: 'getBatchingColor',
  9939. type: 'vec3',
  9940. inputs: [
  9941. { name: 'id', type: 'int' }
  9942. ]
  9943. } );
  9944. const color = getBatchingColor( indirectId );
  9945. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9946. }
  9947. const bm = mat3( batchingMatrix );
  9948. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9949. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9950. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9951. normalLocal.assign( batchingNormal );
  9952. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9953. tangentLocal.mulAssign( bm );
  9954. }
  9955. }
  9956. }
  9957. /**
  9958. * TSL function for creating a batch node.
  9959. *
  9960. * @tsl
  9961. * @function
  9962. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9963. * @returns {BatchNode}
  9964. */
  9965. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9966. const _frameId = new WeakMap();
  9967. /**
  9968. * This node implements the vertex transformation shader logic which is required
  9969. * for skinning/skeletal animation.
  9970. *
  9971. * @augments Node
  9972. */
  9973. class SkinningNode extends Node {
  9974. static get type() {
  9975. return 'SkinningNode';
  9976. }
  9977. /**
  9978. * Constructs a new skinning node.
  9979. *
  9980. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9981. * @param {boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9982. */
  9983. constructor( skinnedMesh, useReference = false ) {
  9984. super( 'void' );
  9985. /**
  9986. * The skinned mesh.
  9987. *
  9988. * @type {SkinnedMesh}
  9989. */
  9990. this.skinnedMesh = skinnedMesh;
  9991. /**
  9992. * Whether to use reference nodes for internal skinned mesh related data or not.
  9993. * TODO: Explain the purpose of the property.
  9994. *
  9995. * @type {boolean}
  9996. */
  9997. this.useReference = useReference;
  9998. /**
  9999. * The update type overwritten since skinning nodes are updated per object.
  10000. *
  10001. * @type {string}
  10002. */
  10003. this.updateType = NodeUpdateType.OBJECT;
  10004. //
  10005. /**
  10006. * The skin index attribute.
  10007. *
  10008. * @type {AttributeNode}
  10009. */
  10010. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  10011. /**
  10012. * The skin weight attribute.
  10013. *
  10014. * @type {AttributeNode}
  10015. */
  10016. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  10017. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  10018. if ( useReference ) {
  10019. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  10020. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  10021. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10022. } else {
  10023. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  10024. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  10025. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  10026. }
  10027. /**
  10028. * The bind matrix node.
  10029. *
  10030. * @type {Node<mat4>}
  10031. */
  10032. this.bindMatrixNode = bindMatrixNode;
  10033. /**
  10034. * The bind matrix inverse node.
  10035. *
  10036. * @type {Node<mat4>}
  10037. */
  10038. this.bindMatrixInverseNode = bindMatrixInverseNode;
  10039. /**
  10040. * The bind matrices as a uniform buffer node.
  10041. *
  10042. * @type {Node}
  10043. */
  10044. this.boneMatricesNode = boneMatricesNode;
  10045. /**
  10046. * The previous bind matrices as a uniform buffer node.
  10047. * Required for computing motion vectors.
  10048. *
  10049. * @type {?Node}
  10050. * @default null
  10051. */
  10052. this.previousBoneMatricesNode = null;
  10053. }
  10054. /**
  10055. * Transforms the given vertex position via skinning.
  10056. *
  10057. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  10058. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  10059. * @return {Node<vec3>} The transformed vertex position.
  10060. */
  10061. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  10062. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  10063. const boneMatX = boneMatrices.element( skinIndexNode.x );
  10064. const boneMatY = boneMatrices.element( skinIndexNode.y );
  10065. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  10066. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10067. // POSITION
  10068. const skinVertex = bindMatrixNode.mul( position );
  10069. const skinned = add(
  10070. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  10071. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  10072. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  10073. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  10074. );
  10075. return bindMatrixInverseNode.mul( skinned ).xyz;
  10076. }
  10077. /**
  10078. * Transforms the given vertex normal via skinning.
  10079. *
  10080. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  10081. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  10082. * @return {Node<vec3>} The transformed vertex normal.
  10083. */
  10084. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  10085. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  10086. const boneMatX = boneMatrices.element( skinIndexNode.x );
  10087. const boneMatY = boneMatrices.element( skinIndexNode.y );
  10088. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  10089. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10090. // NORMAL
  10091. let skinMatrix = add(
  10092. skinWeightNode.x.mul( boneMatX ),
  10093. skinWeightNode.y.mul( boneMatY ),
  10094. skinWeightNode.z.mul( boneMatZ ),
  10095. skinWeightNode.w.mul( boneMatW )
  10096. );
  10097. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  10098. return skinMatrix.transformDirection( normal ).xyz;
  10099. }
  10100. /**
  10101. * Transforms the given vertex normal via skinning.
  10102. *
  10103. * @param {NodeBuilder} builder - The current node builder.
  10104. * @return {Node<vec3>} The skinned position from the previous frame.
  10105. */
  10106. getPreviousSkinnedPosition( builder ) {
  10107. const skinnedMesh = builder.object;
  10108. if ( this.previousBoneMatricesNode === null ) {
  10109. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  10110. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10111. }
  10112. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  10113. }
  10114. /**
  10115. * Returns `true` if bone matrices from the previous frame are required.
  10116. *
  10117. * @param {NodeBuilder} builder - The current node builder.
  10118. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  10119. */
  10120. needsPreviousBoneMatrices( builder ) {
  10121. const mrt = builder.renderer.getMRT();
  10122. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  10123. }
  10124. /**
  10125. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  10126. *
  10127. * @param {NodeBuilder} builder - The current node builder.
  10128. */
  10129. setup( builder ) {
  10130. if ( this.needsPreviousBoneMatrices( builder ) ) {
  10131. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  10132. }
  10133. const skinPosition = this.getSkinnedPosition();
  10134. positionLocal.assign( skinPosition );
  10135. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10136. const skinNormal = this.getSkinnedNormal();
  10137. normalLocal.assign( skinNormal );
  10138. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10139. tangentLocal.assign( skinNormal );
  10140. }
  10141. }
  10142. }
  10143. /**
  10144. * Generates the code snippet of the skinning node.
  10145. *
  10146. * @param {NodeBuilder} builder - The current node builder.
  10147. * @param {string} output - The current output.
  10148. * @return {string} The generated code snippet.
  10149. */
  10150. generate( builder, output ) {
  10151. if ( output !== 'void' ) {
  10152. return positionLocal.build( builder, output );
  10153. }
  10154. }
  10155. /**
  10156. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  10157. *
  10158. * @param {NodeFrame} frame - The current node frame.
  10159. */
  10160. update( frame ) {
  10161. const object = this.useReference ? frame.object : this.skinnedMesh;
  10162. const skeleton = object.skeleton;
  10163. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  10164. _frameId.set( skeleton, frame.frameId );
  10165. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  10166. skeleton.update();
  10167. }
  10168. }
  10169. /**
  10170. * TSL function for creating a skinning node.
  10171. *
  10172. * @tsl
  10173. * @function
  10174. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10175. * @returns {SkinningNode}
  10176. */
  10177. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  10178. /**
  10179. * TSL function for creating a skinning node with reference usage.
  10180. *
  10181. * @tsl
  10182. * @function
  10183. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10184. * @returns {SkinningNode}
  10185. */
  10186. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  10187. /**
  10188. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  10189. * ```js
  10190. * Loop( count, ( { i } ) => {
  10191. *
  10192. * } );
  10193. * ```
  10194. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  10195. * ```js
  10196. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  10197. *
  10198. * } );
  10199. *```
  10200. * Nested loops can be defined in a compacted form:
  10201. * ```js
  10202. * Loop( 10, 5, ( { i, j } ) => {
  10203. *
  10204. * } );
  10205. * ```
  10206. * Loops that should run backwards can be defined like so:
  10207. * ```js
  10208. * Loop( { start: 10 }, () => {} );
  10209. * ```
  10210. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  10211. * @augments Node
  10212. */
  10213. class LoopNode extends Node {
  10214. static get type() {
  10215. return 'LoopNode';
  10216. }
  10217. /**
  10218. * Constructs a new loop node.
  10219. *
  10220. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  10221. */
  10222. constructor( params = [] ) {
  10223. super();
  10224. this.params = params;
  10225. }
  10226. /**
  10227. * Returns a loop variable name based on an index. The pattern is
  10228. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  10229. *
  10230. * @param {number} index - The index.
  10231. * @return {string} The loop variable name.
  10232. */
  10233. getVarName( index ) {
  10234. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  10235. }
  10236. /**
  10237. * Returns properties about this node.
  10238. *
  10239. * @param {NodeBuilder} builder - The current node builder.
  10240. * @return {Object} The node properties.
  10241. */
  10242. getProperties( builder ) {
  10243. const properties = builder.getNodeProperties( this );
  10244. if ( properties.stackNode !== undefined ) return properties;
  10245. //
  10246. const inputs = {};
  10247. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  10248. const param = this.params[ i ];
  10249. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  10250. const type = ( param.isNode !== true && param.type ) || 'int';
  10251. inputs[ name ] = expression( name, type );
  10252. }
  10253. const stack = builder.addStack(); // TODO: cache() it
  10254. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  10255. properties.stackNode = stack;
  10256. builder.removeStack();
  10257. return properties;
  10258. }
  10259. /**
  10260. * This method is overwritten since the node type is inferred based on the loop configuration.
  10261. *
  10262. * @param {NodeBuilder} builder - The current node builder.
  10263. * @return {string} The node type.
  10264. */
  10265. getNodeType( builder ) {
  10266. const { returnsNode } = this.getProperties( builder );
  10267. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  10268. }
  10269. setup( builder ) {
  10270. // setup properties
  10271. this.getProperties( builder );
  10272. }
  10273. generate( builder ) {
  10274. const properties = this.getProperties( builder );
  10275. const params = this.params;
  10276. const stackNode = properties.stackNode;
  10277. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  10278. const param = params[ i ];
  10279. let start = null, end = null, name = null, type = null, condition = null, update = null;
  10280. if ( param.isNode ) {
  10281. type = 'int';
  10282. name = this.getVarName( i );
  10283. start = '0';
  10284. end = param.build( builder, type );
  10285. condition = '<';
  10286. } else {
  10287. type = param.type || 'int';
  10288. name = param.name || this.getVarName( i );
  10289. start = param.start;
  10290. end = param.end;
  10291. condition = param.condition;
  10292. update = param.update;
  10293. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  10294. else if ( start && start.isNode ) start = start.build( builder, type );
  10295. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  10296. else if ( end && end.isNode ) end = end.build( builder, type );
  10297. if ( start !== undefined && end === undefined ) {
  10298. start = start + ' - 1';
  10299. end = '0';
  10300. condition = '>=';
  10301. } else if ( end !== undefined && start === undefined ) {
  10302. start = '0';
  10303. condition = '<';
  10304. }
  10305. if ( condition === undefined ) {
  10306. if ( Number( start ) > Number( end ) ) {
  10307. condition = '>=';
  10308. } else {
  10309. condition = '<';
  10310. }
  10311. }
  10312. }
  10313. const internalParam = { start, end};
  10314. //
  10315. const startSnippet = internalParam.start;
  10316. const endSnippet = internalParam.end;
  10317. let declarationSnippet = '';
  10318. let conditionalSnippet = '';
  10319. let updateSnippet = '';
  10320. if ( ! update ) {
  10321. if ( type === 'int' || type === 'uint' ) {
  10322. if ( condition.includes( '<' ) ) update = '++';
  10323. else update = '--';
  10324. } else {
  10325. if ( condition.includes( '<' ) ) update = '+= 1.';
  10326. else update = '-= 1.';
  10327. }
  10328. }
  10329. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  10330. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  10331. updateSnippet += name + ' ' + update;
  10332. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  10333. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  10334. }
  10335. const stackSnippet = stackNode.build( builder, 'void' );
  10336. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  10337. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  10338. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  10339. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  10340. }
  10341. builder.addFlowTab();
  10342. return returnsSnippet;
  10343. }
  10344. }
  10345. /**
  10346. * TSL function for creating a loop node.
  10347. *
  10348. * @tsl
  10349. * @function
  10350. * @param {...any} params - A list of parameters.
  10351. * @returns {LoopNode}
  10352. */
  10353. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  10354. /**
  10355. * TSL function for creating a `Continue()` expression.
  10356. *
  10357. * @tsl
  10358. * @function
  10359. * @returns {ExpressionNode}
  10360. */
  10361. const Continue = () => expression( 'continue' ).append();
  10362. /**
  10363. * TSL function for creating a `Break()` expression.
  10364. *
  10365. * @tsl
  10366. * @function
  10367. * @returns {ExpressionNode}
  10368. */
  10369. const Break = () => expression( 'break' ).append();
  10370. // Deprecated
  10371. /**
  10372. * @tsl
  10373. * @function
  10374. * @deprecated since r168. Use {@link Loop} instead.
  10375. *
  10376. * @param {...any} params
  10377. * @returns {LoopNode}
  10378. */
  10379. const loop = ( ...params ) => { // @deprecated, r168
  10380. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  10381. return Loop( ...params );
  10382. };
  10383. const _morphTextures = /*@__PURE__*/ new WeakMap();
  10384. const _morphVec4 = /*@__PURE__*/ new Vector4();
  10385. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  10386. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  10387. const y = texelIndex.div( width );
  10388. const x = texelIndex.sub( y.mul( width ) );
  10389. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  10390. return bufferAttrib.mul( influence );
  10391. } );
  10392. function getEntry( geometry ) {
  10393. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10394. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10395. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10396. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10397. // into an array of data textures. Each layer represents a single morph target.
  10398. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10399. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10400. let entry = _morphTextures.get( geometry );
  10401. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10402. if ( entry !== undefined ) entry.texture.dispose();
  10403. const morphTargets = geometry.morphAttributes.position || [];
  10404. const morphNormals = geometry.morphAttributes.normal || [];
  10405. const morphColors = geometry.morphAttributes.color || [];
  10406. let vertexDataCount = 0;
  10407. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10408. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10409. if ( hasMorphColors === true ) vertexDataCount = 3;
  10410. let width = geometry.attributes.position.count * vertexDataCount;
  10411. let height = 1;
  10412. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  10413. if ( width > maxTextureSize ) {
  10414. height = Math.ceil( width / maxTextureSize );
  10415. width = maxTextureSize;
  10416. }
  10417. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10418. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10419. bufferTexture.type = FloatType;
  10420. bufferTexture.needsUpdate = true;
  10421. // fill buffer
  10422. const vertexDataStride = vertexDataCount * 4;
  10423. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10424. const morphTarget = morphTargets[ i ];
  10425. const morphNormal = morphNormals[ i ];
  10426. const morphColor = morphColors[ i ];
  10427. const offset = width * height * 4 * i;
  10428. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10429. const stride = j * vertexDataStride;
  10430. if ( hasMorphPosition === true ) {
  10431. _morphVec4.fromBufferAttribute( morphTarget, j );
  10432. buffer[ offset + stride + 0 ] = _morphVec4.x;
  10433. buffer[ offset + stride + 1 ] = _morphVec4.y;
  10434. buffer[ offset + stride + 2 ] = _morphVec4.z;
  10435. buffer[ offset + stride + 3 ] = 0;
  10436. }
  10437. if ( hasMorphNormals === true ) {
  10438. _morphVec4.fromBufferAttribute( morphNormal, j );
  10439. buffer[ offset + stride + 4 ] = _morphVec4.x;
  10440. buffer[ offset + stride + 5 ] = _morphVec4.y;
  10441. buffer[ offset + stride + 6 ] = _morphVec4.z;
  10442. buffer[ offset + stride + 7 ] = 0;
  10443. }
  10444. if ( hasMorphColors === true ) {
  10445. _morphVec4.fromBufferAttribute( morphColor, j );
  10446. buffer[ offset + stride + 8 ] = _morphVec4.x;
  10447. buffer[ offset + stride + 9 ] = _morphVec4.y;
  10448. buffer[ offset + stride + 10 ] = _morphVec4.z;
  10449. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  10450. }
  10451. }
  10452. }
  10453. entry = {
  10454. count: morphTargetsCount,
  10455. texture: bufferTexture,
  10456. stride: vertexDataCount,
  10457. size: new Vector2( width, height )
  10458. };
  10459. _morphTextures.set( geometry, entry );
  10460. function disposeTexture() {
  10461. bufferTexture.dispose();
  10462. _morphTextures.delete( geometry );
  10463. geometry.removeEventListener( 'dispose', disposeTexture );
  10464. }
  10465. geometry.addEventListener( 'dispose', disposeTexture );
  10466. }
  10467. return entry;
  10468. }
  10469. /**
  10470. * This node implements the vertex transformation shader logic which is required
  10471. * for morph target animation.
  10472. *
  10473. * @augments Node
  10474. */
  10475. class MorphNode extends Node {
  10476. static get type() {
  10477. return 'MorphNode';
  10478. }
  10479. /**
  10480. * Constructs a new morph node.
  10481. *
  10482. * @param {Mesh} mesh - The mesh holding the morph targets.
  10483. */
  10484. constructor( mesh ) {
  10485. super( 'void' );
  10486. /**
  10487. * The mesh holding the morph targets.
  10488. *
  10489. * @type {Mesh}
  10490. */
  10491. this.mesh = mesh;
  10492. /**
  10493. * A uniform node which represents the morph base influence value.
  10494. *
  10495. * @type {UniformNode<float>}
  10496. */
  10497. this.morphBaseInfluence = uniform( 1 );
  10498. /**
  10499. * The update type overwritten since morph nodes are updated per object.
  10500. *
  10501. * @type {string}
  10502. */
  10503. this.updateType = NodeUpdateType.OBJECT;
  10504. }
  10505. /**
  10506. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  10507. *
  10508. * @param {NodeBuilder} builder - The current node builder.
  10509. */
  10510. setup( builder ) {
  10511. const { geometry } = builder;
  10512. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10513. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  10514. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10515. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10516. // nodes
  10517. const { texture: bufferMap, stride, size } = getEntry( geometry );
  10518. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  10519. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  10520. const width = int( size.width );
  10521. Loop( morphTargetsCount, ( { i } ) => {
  10522. const influence = float( 0 ).toVar();
  10523. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  10524. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  10525. } else {
  10526. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  10527. }
  10528. if ( hasMorphPosition === true ) {
  10529. positionLocal.addAssign( getMorph( {
  10530. bufferMap,
  10531. influence,
  10532. stride,
  10533. width,
  10534. depth: i,
  10535. offset: int( 0 )
  10536. } ) );
  10537. }
  10538. if ( hasMorphNormals === true ) {
  10539. normalLocal.addAssign( getMorph( {
  10540. bufferMap,
  10541. influence,
  10542. stride,
  10543. width,
  10544. depth: i,
  10545. offset: int( 1 )
  10546. } ) );
  10547. }
  10548. } );
  10549. }
  10550. /**
  10551. * Updates the state of the morphed mesh by updating the base influence.
  10552. *
  10553. * @param {NodeFrame} frame - The current node frame.
  10554. */
  10555. update( /*frame*/ ) {
  10556. const morphBaseInfluence = this.morphBaseInfluence;
  10557. if ( this.mesh.geometry.morphTargetsRelative ) {
  10558. morphBaseInfluence.value = 1;
  10559. } else {
  10560. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10561. }
  10562. }
  10563. }
  10564. /**
  10565. * TSL function for creating a morph node.
  10566. *
  10567. * @tsl
  10568. * @function
  10569. * @param {Mesh} mesh - The mesh holding the morph targets.
  10570. * @returns {MorphNode}
  10571. */
  10572. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10573. /**
  10574. * Base class for lighting nodes.
  10575. *
  10576. * @augments Node
  10577. */
  10578. class LightingNode extends Node {
  10579. static get type() {
  10580. return 'LightingNode';
  10581. }
  10582. /**
  10583. * Constructs a new lighting node.
  10584. */
  10585. constructor() {
  10586. super( 'vec3' );
  10587. /**
  10588. * This flag can be used for type testing.
  10589. *
  10590. * @type {boolean}
  10591. * @readonly
  10592. * @default true
  10593. */
  10594. this.isLightingNode = true;
  10595. }
  10596. }
  10597. /**
  10598. * A generic class that can be used by nodes which contribute
  10599. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10600. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10601. *
  10602. * @augments LightingNode
  10603. */
  10604. class AONode extends LightingNode {
  10605. static get type() {
  10606. return 'AONode';
  10607. }
  10608. /**
  10609. * Constructs a new AO node.
  10610. *
  10611. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  10612. */
  10613. constructor( aoNode = null ) {
  10614. super();
  10615. /**
  10616. * The ambient occlusion node.
  10617. *
  10618. * @type {?Node<float>}
  10619. * @default null
  10620. */
  10621. this.aoNode = aoNode;
  10622. }
  10623. setup( builder ) {
  10624. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10625. }
  10626. }
  10627. /**
  10628. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  10629. * by adding lighting specific context data. It represents the runtime context of
  10630. * {@link LightsNode}.
  10631. *
  10632. * @augments ContextNode
  10633. */
  10634. class LightingContextNode extends ContextNode {
  10635. static get type() {
  10636. return 'LightingContextNode';
  10637. }
  10638. /**
  10639. * Constructs a new lighting context node.
  10640. *
  10641. * @param {LightsNode} lightsNode - The lights node.
  10642. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  10643. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  10644. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  10645. */
  10646. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10647. super( lightsNode );
  10648. /**
  10649. * The current lighting model.
  10650. *
  10651. * @type {?LightingModel}
  10652. * @default null
  10653. */
  10654. this.lightingModel = lightingModel;
  10655. /**
  10656. * A backdrop node.
  10657. *
  10658. * @type {?Node<vec3>}
  10659. * @default null
  10660. */
  10661. this.backdropNode = backdropNode;
  10662. /**
  10663. * A backdrop alpha node.
  10664. *
  10665. * @type {?Node<float>}
  10666. * @default null
  10667. */
  10668. this.backdropAlphaNode = backdropAlphaNode;
  10669. this._value = null;
  10670. }
  10671. /**
  10672. * Returns a lighting context object.
  10673. *
  10674. * @return {{
  10675. * radiance: Node<vec3>,
  10676. * irradiance: Node<vec3>,
  10677. * iblIrradiance: Node<vec3>,
  10678. * ambientOcclusion: Node<float>,
  10679. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10680. * backdrop: Node<vec3>,
  10681. * backdropAlpha: Node<float>
  10682. * }} The lighting context object.
  10683. */
  10684. getContext() {
  10685. const { backdropNode, backdropAlphaNode } = this;
  10686. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10687. directSpecular = vec3().toVar( 'directSpecular' ),
  10688. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10689. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10690. const reflectedLight = {
  10691. directDiffuse,
  10692. directSpecular,
  10693. indirectDiffuse,
  10694. indirectSpecular
  10695. };
  10696. const context = {
  10697. radiance: vec3().toVar( 'radiance' ),
  10698. irradiance: vec3().toVar( 'irradiance' ),
  10699. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10700. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10701. reflectedLight,
  10702. backdrop: backdropNode,
  10703. backdropAlpha: backdropAlphaNode
  10704. };
  10705. return context;
  10706. }
  10707. setup( builder ) {
  10708. this.value = this._value || ( this._value = this.getContext() );
  10709. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10710. return super.setup( builder );
  10711. }
  10712. }
  10713. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10714. /**
  10715. * A generic class that can be used by nodes which contribute
  10716. * irradiance to the scene. E.g. a light map node can be used
  10717. * as input for this module. Used in {@link NodeMaterial}.
  10718. *
  10719. * @augments LightingNode
  10720. */
  10721. class IrradianceNode extends LightingNode {
  10722. static get type() {
  10723. return 'IrradianceNode';
  10724. }
  10725. /**
  10726. * Constructs a new irradiance node.
  10727. *
  10728. * @param {Node<vec3>} node - A node contributing irradiance.
  10729. */
  10730. constructor( node ) {
  10731. super();
  10732. /**
  10733. * A node contributing irradiance.
  10734. *
  10735. * @type {Node<vec3>}
  10736. */
  10737. this.node = node;
  10738. }
  10739. setup( builder ) {
  10740. builder.context.irradiance.addAssign( this.node );
  10741. }
  10742. }
  10743. let screenSizeVec, viewportVec;
  10744. /**
  10745. * This node provides a collection of screen related metrics.
  10746. * Depending on {@link ScreenNode#scope}, the nodes can represent
  10747. * resolution or viewport data as well as fragment or uv coordinates.
  10748. *
  10749. * @augments Node
  10750. */
  10751. class ScreenNode extends Node {
  10752. static get type() {
  10753. return 'ScreenNode';
  10754. }
  10755. /**
  10756. * Constructs a new screen node.
  10757. *
  10758. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10759. */
  10760. constructor( scope ) {
  10761. super();
  10762. /**
  10763. * The node represents different metric depending on which scope is selected.
  10764. *
  10765. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10766. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10767. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10768. * - `ScreenNode.UV`: Normalized coordinates.
  10769. *
  10770. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10771. */
  10772. this.scope = scope;
  10773. /**
  10774. * This flag can be used for type testing.
  10775. *
  10776. * @type {boolean}
  10777. * @readonly
  10778. * @default true
  10779. */
  10780. this.isViewportNode = true;
  10781. }
  10782. /**
  10783. * This method is overwritten since the node type depends on the selected scope.
  10784. *
  10785. * @return {('vec2'|'vec4')} The node type.
  10786. */
  10787. getNodeType() {
  10788. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10789. else return 'vec2';
  10790. }
  10791. /**
  10792. * This method is overwritten since the node's update type depends on the selected scope.
  10793. *
  10794. * @return {NodeUpdateType} The update type.
  10795. */
  10796. getUpdateType() {
  10797. let updateType = NodeUpdateType.NONE;
  10798. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10799. updateType = NodeUpdateType.RENDER;
  10800. }
  10801. this.updateType = updateType;
  10802. return updateType;
  10803. }
  10804. /**
  10805. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10806. * from the current renderer.
  10807. *
  10808. * @param {NodeFrame} frame - A reference to the current node frame.
  10809. */
  10810. update( { renderer } ) {
  10811. const renderTarget = renderer.getRenderTarget();
  10812. if ( this.scope === ScreenNode.VIEWPORT ) {
  10813. if ( renderTarget !== null ) {
  10814. viewportVec.copy( renderTarget.viewport );
  10815. } else {
  10816. renderer.getViewport( viewportVec );
  10817. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10818. }
  10819. } else {
  10820. if ( renderTarget !== null ) {
  10821. screenSizeVec.width = renderTarget.width;
  10822. screenSizeVec.height = renderTarget.height;
  10823. } else {
  10824. renderer.getDrawingBufferSize( screenSizeVec );
  10825. }
  10826. }
  10827. }
  10828. setup( /*builder*/ ) {
  10829. const scope = this.scope;
  10830. let output = null;
  10831. if ( scope === ScreenNode.SIZE ) {
  10832. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10833. } else if ( scope === ScreenNode.VIEWPORT ) {
  10834. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10835. } else {
  10836. output = vec2( screenCoordinate.div( screenSize ) );
  10837. }
  10838. return output;
  10839. }
  10840. generate( builder ) {
  10841. if ( this.scope === ScreenNode.COORDINATE ) {
  10842. let coord = builder.getFragCoord();
  10843. if ( builder.isFlipY() ) {
  10844. // follow webgpu standards
  10845. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10846. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10847. }
  10848. return coord;
  10849. }
  10850. return super.generate( builder );
  10851. }
  10852. }
  10853. ScreenNode.COORDINATE = 'coordinate';
  10854. ScreenNode.VIEWPORT = 'viewport';
  10855. ScreenNode.SIZE = 'size';
  10856. ScreenNode.UV = 'uv';
  10857. // Screen
  10858. /**
  10859. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10860. *
  10861. * @tsl
  10862. * @type {ScreenNode<vec2>}
  10863. */
  10864. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10865. /**
  10866. * TSL object that represents the screen resolution in physical pixel units.
  10867. *
  10868. * @tsl
  10869. * @type {ScreenNode<vec2>}
  10870. */
  10871. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10872. /**
  10873. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10874. *
  10875. * @tsl
  10876. * @type {ScreenNode<vec2>}
  10877. */
  10878. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10879. // Viewport
  10880. /**
  10881. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10882. *
  10883. * @tsl
  10884. * @type {ScreenNode<vec4>}
  10885. */
  10886. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10887. /**
  10888. * TSL object that represents the viewport resolution in physical pixel units.
  10889. *
  10890. * @tsl
  10891. * @type {ScreenNode<vec2>}
  10892. */
  10893. const viewportSize = viewport.zw;
  10894. /**
  10895. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10896. *
  10897. * @tsl
  10898. * @type {ScreenNode<vec2>}
  10899. */
  10900. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10901. /**
  10902. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10903. *
  10904. * @tsl
  10905. * @type {ScreenNode<vec2>}
  10906. */
  10907. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10908. // Deprecated
  10909. /**
  10910. * @deprecated since r169. Use {@link screenSize} instead.
  10911. */
  10912. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10913. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10914. return screenSize;
  10915. }, 'vec2' ).once() )();
  10916. /**
  10917. * @tsl
  10918. * @deprecated since r168. Use {@link screenUV} instead.
  10919. * @type {Node<vec2>}
  10920. */
  10921. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10922. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10923. return screenUV;
  10924. }, 'vec2' ).once() )();
  10925. /**
  10926. * @tsl
  10927. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10928. * @type {Node<vec2>}
  10929. */
  10930. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10931. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10932. return screenUV.flipY();
  10933. }, 'vec2' ).once() )();
  10934. const _size$4 = /*@__PURE__*/ new Vector2();
  10935. /**
  10936. * A special type of texture node which represents the data of the current viewport
  10937. * as a texture. The module extracts data from the current bound framebuffer with
  10938. * a copy operation so no extra render pass is required to produce the texture data
  10939. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10940. * variety of effects like refractive or transmissive materials.
  10941. *
  10942. * @augments TextureNode
  10943. */
  10944. class ViewportTextureNode extends TextureNode {
  10945. static get type() {
  10946. return 'ViewportTextureNode';
  10947. }
  10948. /**
  10949. * Constructs a new viewport texture node.
  10950. *
  10951. * @param {Node} [uvNode=screenUV] - The uv node.
  10952. * @param {?Node} [levelNode=null] - The level node.
  10953. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10954. */
  10955. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10956. if ( framebufferTexture === null ) {
  10957. framebufferTexture = new FramebufferTexture();
  10958. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10959. }
  10960. super( framebufferTexture, uvNode, levelNode );
  10961. /**
  10962. * Whether to generate mipmaps or not.
  10963. *
  10964. * @type {boolean}
  10965. * @default false
  10966. */
  10967. this.generateMipmaps = false;
  10968. /**
  10969. * This flag can be used for type testing.
  10970. *
  10971. * @type {boolean}
  10972. * @readonly
  10973. * @default true
  10974. */
  10975. this.isOutputTextureNode = true;
  10976. /**
  10977. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10978. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10979. *
  10980. * @type {string}
  10981. * @default 'frame'
  10982. */
  10983. this.updateBeforeType = NodeUpdateType.FRAME;
  10984. }
  10985. updateBefore( frame ) {
  10986. const renderer = frame.renderer;
  10987. renderer.getDrawingBufferSize( _size$4 );
  10988. //
  10989. const framebufferTexture = this.value;
  10990. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10991. framebufferTexture.image.width = _size$4.width;
  10992. framebufferTexture.image.height = _size$4.height;
  10993. framebufferTexture.needsUpdate = true;
  10994. }
  10995. //
  10996. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10997. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10998. renderer.copyFramebufferToTexture( framebufferTexture );
  10999. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  11000. }
  11001. clone() {
  11002. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  11003. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  11004. return viewportTextureNode;
  11005. }
  11006. }
  11007. /**
  11008. * TSL function for creating a viewport texture node.
  11009. *
  11010. * @tsl
  11011. * @function
  11012. * @param {Node} [uvNode=screenUV] - The uv node.
  11013. * @param {?Node} [levelNode=null] - The level node.
  11014. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11015. * @returns {ViewportTextureNode}
  11016. */
  11017. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  11018. /**
  11019. * TSL function for creating a viewport texture node with enabled mipmap generation.
  11020. *
  11021. * @tsl
  11022. * @function
  11023. * @param {Node} [uvNode=screenUV] - The uv node.
  11024. * @param {?Node} [levelNode=null] - The level node.
  11025. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11026. * @returns {ViewportTextureNode}
  11027. */
  11028. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  11029. let sharedDepthbuffer = null;
  11030. /**
  11031. * Represents the depth of the current viewport as a texture. This module
  11032. * can be used in combination with viewport texture to achieve effects
  11033. * that require depth evaluation.
  11034. *
  11035. * @augments ViewportTextureNode
  11036. */
  11037. class ViewportDepthTextureNode extends ViewportTextureNode {
  11038. static get type() {
  11039. return 'ViewportDepthTextureNode';
  11040. }
  11041. /**
  11042. * Constructs a new viewport depth texture node.
  11043. *
  11044. * @param {Node} [uvNode=screenUV] - The uv node.
  11045. * @param {?Node} [levelNode=null] - The level node.
  11046. */
  11047. constructor( uvNode = screenUV, levelNode = null ) {
  11048. if ( sharedDepthbuffer === null ) {
  11049. sharedDepthbuffer = new DepthTexture();
  11050. }
  11051. super( uvNode, levelNode, sharedDepthbuffer );
  11052. }
  11053. }
  11054. /**
  11055. * TSL function for a viewport depth texture node.
  11056. *
  11057. * @tsl
  11058. * @function
  11059. * @param {Node} [uvNode=screenUV] - The uv node.
  11060. * @param {?Node} [levelNode=null] - The level node.
  11061. * @returns {ViewportDepthTextureNode}
  11062. */
  11063. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  11064. /**
  11065. * This node offers a collection of features in context of the depth logic in the fragment shader.
  11066. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  11067. * fragment or for depth evaluation purposes.
  11068. *
  11069. * @augments Node
  11070. */
  11071. class ViewportDepthNode extends Node {
  11072. static get type() {
  11073. return 'ViewportDepthNode';
  11074. }
  11075. /**
  11076. * Constructs a new viewport depth node.
  11077. *
  11078. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  11079. * @param {?Node} [valueNode=null] - The value node.
  11080. */
  11081. constructor( scope, valueNode = null ) {
  11082. super( 'float' );
  11083. /**
  11084. * The node behaves differently depending on which scope is selected.
  11085. *
  11086. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  11087. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  11088. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  11089. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  11090. *
  11091. * @type {('depth'|'depthBase'|'linearDepth')}
  11092. */
  11093. this.scope = scope;
  11094. /**
  11095. * Can be used to define a custom depth value.
  11096. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  11097. *
  11098. * @type {?Node}
  11099. * @default null
  11100. */
  11101. this.valueNode = valueNode;
  11102. /**
  11103. * This flag can be used for type testing.
  11104. *
  11105. * @type {boolean}
  11106. * @readonly
  11107. * @default true
  11108. */
  11109. this.isViewportDepthNode = true;
  11110. }
  11111. generate( builder ) {
  11112. const { scope } = this;
  11113. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11114. return builder.getFragDepth();
  11115. }
  11116. return super.generate( builder );
  11117. }
  11118. setup( { camera } ) {
  11119. const { scope } = this;
  11120. const value = this.valueNode;
  11121. let node = null;
  11122. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11123. if ( value !== null ) {
  11124. node = depthBase().assign( value );
  11125. }
  11126. } else if ( scope === ViewportDepthNode.DEPTH ) {
  11127. if ( camera.isPerspectiveCamera ) {
  11128. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  11129. } else {
  11130. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11131. }
  11132. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  11133. if ( value !== null ) {
  11134. if ( camera.isPerspectiveCamera ) {
  11135. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  11136. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  11137. } else {
  11138. node = value;
  11139. }
  11140. } else {
  11141. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11142. }
  11143. }
  11144. return node;
  11145. }
  11146. }
  11147. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  11148. ViewportDepthNode.DEPTH = 'depth';
  11149. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  11150. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  11151. /**
  11152. * TSL function for converting a viewZ value to an orthographic depth value.
  11153. *
  11154. * @tsl
  11155. * @function
  11156. * @param {Node<float>} viewZ - The viewZ node.
  11157. * @param {Node<float>} near - The camera's near value.
  11158. * @param {Node<float>} far - The camera's far value.
  11159. * @returns {Node<float>}
  11160. */
  11161. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  11162. /**
  11163. * TSL function for converting an orthographic depth value to a viewZ value.
  11164. *
  11165. * @tsl
  11166. * @function
  11167. * @param {Node<float>} depth - The orthographic depth.
  11168. * @param {Node<float>} near - The camera's near value.
  11169. * @param {Node<float>} far - The camera's far value.
  11170. * @returns {Node<float>}
  11171. */
  11172. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  11173. /**
  11174. * TSL function for converting a viewZ value to a perspective depth value.
  11175. *
  11176. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  11177. *
  11178. * @tsl
  11179. * @function
  11180. * @param {Node<float>} viewZ - The viewZ node.
  11181. * @param {Node<float>} near - The camera's near value.
  11182. * @param {Node<float>} far - The camera's far value.
  11183. * @returns {Node<float>}
  11184. */
  11185. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  11186. /**
  11187. * TSL function for converting a perspective depth value to a viewZ value.
  11188. *
  11189. * @tsl
  11190. * @function
  11191. * @param {Node<float>} depth - The perspective depth.
  11192. * @param {Node<float>} near - The camera's near value.
  11193. * @param {Node<float>} far - The camera's far value.
  11194. * @returns {Node<float>}
  11195. */
  11196. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  11197. /**
  11198. * TSL function for converting a viewZ value to a logarithmic depth value.
  11199. *
  11200. * @tsl
  11201. * @function
  11202. * @param {Node<float>} viewZ - The viewZ node.
  11203. * @param {Node<float>} near - The camera's near value.
  11204. * @param {Node<float>} far - The camera's far value.
  11205. * @returns {Node<float>}
  11206. */
  11207. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  11208. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  11209. // The final logarithmic depth formula used here is adapted from one described in an
  11210. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  11211. // which was an improvement upon an earlier formula one described in an
  11212. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  11213. // Ulrich's formula is the following:
  11214. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  11215. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  11216. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  11217. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  11218. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  11219. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  11220. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  11221. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  11222. // be used, and ultimately Ulrich's "near plane" version was chosen.
  11223. // Outerra eventually made another improvement to their original "C-constant" variant,
  11224. // but it still does not incorporate the camera near plane (for this version,
  11225. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  11226. // Here we make 4 changes to Ulrich's formula:
  11227. // 1. Clamp the camera near plane so we don't divide by 0.
  11228. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  11229. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  11230. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  11231. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  11232. // so we do the same here, hence the 'viewZ.negate()' call.
  11233. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  11234. near = near.max( 1e-6 ).toVar();
  11235. const numerator = log2( viewZ.negate().div( near ) );
  11236. const denominator = log2( far.div( near ) );
  11237. return numerator.div( denominator );
  11238. };
  11239. /**
  11240. * TSL function for converting a logarithmic depth value to a viewZ value.
  11241. *
  11242. * @tsl
  11243. * @function
  11244. * @param {Node<float>} depth - The logarithmic depth.
  11245. * @param {Node<float>} near - The camera's near value.
  11246. * @param {Node<float>} far - The camera's far value.
  11247. * @returns {Node<float>}
  11248. */
  11249. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  11250. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  11251. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  11252. // a negative viewZ).
  11253. const exponent = depth.mul( log( far.div( near ) ) );
  11254. return float( Math.E ).pow( exponent ).mul( near ).negate();
  11255. };
  11256. /**
  11257. * TSL function for defining a value for the current fragment's depth.
  11258. *
  11259. * @tsl
  11260. * @function
  11261. * @param {Node<float>} value - The depth value to set.
  11262. * @returns {ViewportDepthNode<float>}
  11263. */
  11264. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  11265. /**
  11266. * TSL object that represents the depth value for the current fragment.
  11267. *
  11268. * @tsl
  11269. * @type {ViewportDepthNode}
  11270. */
  11271. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  11272. /**
  11273. * TSL function for converting a perspective depth value to linear depth.
  11274. *
  11275. * @tsl
  11276. * @function
  11277. * @param {Node<float>} value - The perspective depth.
  11278. * @returns {ViewportDepthNode<float>}
  11279. */
  11280. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  11281. /**
  11282. * TSL object that represents the linear (orthographic) depth value of the current fragment
  11283. *
  11284. * @tsl
  11285. * @type {ViewportDepthNode}
  11286. */
  11287. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  11288. depth.assign = ( value ) => depthBase( value );
  11289. /**
  11290. * The node allows to set values for built-in shader variables. That is
  11291. * required for features like hardware-accelerated vertex clipping.
  11292. *
  11293. * @augments Node
  11294. */
  11295. class BuiltinNode extends Node {
  11296. /**
  11297. * Constructs a new builtin node.
  11298. *
  11299. * @param {string} name - The name of the built-in shader variable.
  11300. */
  11301. constructor( name ) {
  11302. super( 'float' );
  11303. /**
  11304. * The name of the built-in shader variable.
  11305. *
  11306. * @type {string}
  11307. */
  11308. this.name = name;
  11309. /**
  11310. * This flag can be used for type testing.
  11311. *
  11312. * @type {boolean}
  11313. * @readonly
  11314. * @default true
  11315. */
  11316. this.isBuiltinNode = true;
  11317. }
  11318. /**
  11319. * Generates the code snippet of the builtin node.
  11320. *
  11321. * @param {NodeBuilder} builder - The current node builder.
  11322. * @return {string} The generated code snippet.
  11323. */
  11324. generate( /* builder */ ) {
  11325. return this.name;
  11326. }
  11327. }
  11328. /**
  11329. * TSL function for creating a builtin node.
  11330. *
  11331. * @tsl
  11332. * @function
  11333. * @param {string} name - The name of the built-in shader variable.
  11334. * @returns {BuiltinNode}
  11335. */
  11336. const builtin = nodeProxy( BuiltinNode );
  11337. /**
  11338. * This node is used in {@link NodeMaterial} to setup the clipping
  11339. * which can happen hardware-accelerated (if supported) and optionally
  11340. * use alpha-to-coverage for anti-aliasing clipped edges.
  11341. *
  11342. * @augments Node
  11343. */
  11344. class ClippingNode extends Node {
  11345. static get type() {
  11346. return 'ClippingNode';
  11347. }
  11348. /**
  11349. * Constructs a new clipping node.
  11350. *
  11351. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  11352. * the selected scope influences the behavior of the node and what type of code is generated.
  11353. */
  11354. constructor( scope = ClippingNode.DEFAULT ) {
  11355. super();
  11356. /**
  11357. * The node's scope. Similar to other nodes, the selected scope influences
  11358. * the behavior of the node and what type of code is generated.
  11359. *
  11360. * @type {('default'|'hardware'|'alphaToCoverage')}
  11361. */
  11362. this.scope = scope;
  11363. }
  11364. /**
  11365. * Setups the node depending on the selected scope.
  11366. *
  11367. * @param {NodeBuilder} builder - The current node builder.
  11368. * @return {Node} The result node.
  11369. */
  11370. setup( builder ) {
  11371. super.setup( builder );
  11372. const clippingContext = builder.clippingContext;
  11373. const { intersectionPlanes, unionPlanes } = clippingContext;
  11374. this.hardwareClipping = builder.material.hardwareClipping;
  11375. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  11376. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  11377. } else if ( this.scope === ClippingNode.HARDWARE ) {
  11378. return this.setupHardwareClipping( unionPlanes, builder );
  11379. } else {
  11380. return this.setupDefault( intersectionPlanes, unionPlanes );
  11381. }
  11382. }
  11383. /**
  11384. * Setups alpha to coverage.
  11385. *
  11386. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11387. * @param {Array<Vector4>} unionPlanes - The union planes.
  11388. * @return {Node} The result node.
  11389. */
  11390. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  11391. return Fn( () => {
  11392. const distanceToPlane = float().toVar( 'distanceToPlane' );
  11393. const distanceGradient = float().toVar( 'distanceToGradient' );
  11394. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  11395. const numUnionPlanes = unionPlanes.length;
  11396. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11397. const clippingPlanes = uniformArray( unionPlanes );
  11398. Loop( numUnionPlanes, ( { i } ) => {
  11399. const plane = clippingPlanes.element( i );
  11400. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11401. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11402. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  11403. } );
  11404. }
  11405. const numIntersectionPlanes = intersectionPlanes.length;
  11406. if ( numIntersectionPlanes > 0 ) {
  11407. const clippingPlanes = uniformArray( intersectionPlanes );
  11408. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  11409. Loop( numIntersectionPlanes, ( { i } ) => {
  11410. const plane = clippingPlanes.element( i );
  11411. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  11412. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  11413. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  11414. } );
  11415. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  11416. }
  11417. diffuseColor.a.mulAssign( clipOpacity );
  11418. diffuseColor.a.equal( 0.0 ).discard();
  11419. } )();
  11420. }
  11421. /**
  11422. * Setups the default clipping.
  11423. *
  11424. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  11425. * @param {Array<Vector4>} unionPlanes - The union planes.
  11426. * @return {Node} The result node.
  11427. */
  11428. setupDefault( intersectionPlanes, unionPlanes ) {
  11429. return Fn( () => {
  11430. const numUnionPlanes = unionPlanes.length;
  11431. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  11432. const clippingPlanes = uniformArray( unionPlanes );
  11433. Loop( numUnionPlanes, ( { i } ) => {
  11434. const plane = clippingPlanes.element( i );
  11435. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  11436. } );
  11437. }
  11438. const numIntersectionPlanes = intersectionPlanes.length;
  11439. if ( numIntersectionPlanes > 0 ) {
  11440. const clippingPlanes = uniformArray( intersectionPlanes );
  11441. const clipped = bool( true ).toVar( 'clipped' );
  11442. Loop( numIntersectionPlanes, ( { i } ) => {
  11443. const plane = clippingPlanes.element( i );
  11444. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  11445. } );
  11446. clipped.discard();
  11447. }
  11448. } )();
  11449. }
  11450. /**
  11451. * Setups hardware clipping.
  11452. *
  11453. * @param {Array<Vector4>} unionPlanes - The union planes.
  11454. * @param {NodeBuilder} builder - The current node builder.
  11455. * @return {Node} The result node.
  11456. */
  11457. setupHardwareClipping( unionPlanes, builder ) {
  11458. const numUnionPlanes = unionPlanes.length;
  11459. builder.enableHardwareClipping( numUnionPlanes );
  11460. return Fn( () => {
  11461. const clippingPlanes = uniformArray( unionPlanes );
  11462. const hw_clip_distances = builtin( builder.getClipDistance() );
  11463. Loop( numUnionPlanes, ( { i } ) => {
  11464. const plane = clippingPlanes.element( i );
  11465. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  11466. hw_clip_distances.element( i ).assign( distance );
  11467. } );
  11468. } )();
  11469. }
  11470. }
  11471. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  11472. ClippingNode.DEFAULT = 'default';
  11473. ClippingNode.HARDWARE = 'hardware';
  11474. /**
  11475. * TSL function for setting up the default clipping logic.
  11476. *
  11477. * @tsl
  11478. * @function
  11479. * @returns {ClippingNode}
  11480. */
  11481. const clipping = () => nodeObject( new ClippingNode() );
  11482. /**
  11483. * TSL function for setting up alpha to coverage.
  11484. *
  11485. * @tsl
  11486. * @function
  11487. * @returns {ClippingNode}
  11488. */
  11489. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  11490. /**
  11491. * TSL function for setting up hardware-based clipping.
  11492. *
  11493. * @tsl
  11494. * @function
  11495. * @returns {ClippingNode}
  11496. */
  11497. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  11498. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  11499. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  11500. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11501. 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 ) ) ) ) ) );
  11502. } );
  11503. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  11504. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  11505. } );
  11506. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  11507. // Find the discretized derivatives of our coordinates
  11508. const maxDeriv = max$1(
  11509. length( dFdx( position.xyz ) ),
  11510. length( dFdy( position.xyz ) )
  11511. );
  11512. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  11513. // Find two nearest log-discretized noise scales
  11514. const pixScales = vec2(
  11515. exp2( floor( log2( pixScale ) ) ),
  11516. exp2( ceil( log2( pixScale ) ) )
  11517. );
  11518. // Compute alpha thresholds at our two noise scales
  11519. const alpha = vec2(
  11520. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  11521. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  11522. );
  11523. // Factor to interpolate lerp with
  11524. const lerpFactor = fract( log2( pixScale ) );
  11525. // Interpolate alpha threshold from noise at two scales
  11526. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  11527. // Pass into CDF to compute uniformly distrib threshold
  11528. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  11529. const cases = vec3(
  11530. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  11531. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  11532. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  11533. // Find our final, uniformly distributed alpha threshold (ατ)
  11534. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  11535. // Avoids ατ == 0. Could also do ατ =1-ατ
  11536. return clamp( threshold, 1.0e-6, 1.0 );
  11537. } ).setLayout( {
  11538. name: 'getAlphaHashThreshold',
  11539. type: 'float',
  11540. inputs: [
  11541. { name: 'position', type: 'vec3' }
  11542. ]
  11543. } );
  11544. /**
  11545. * Base class for all node materials.
  11546. *
  11547. * @augments Material
  11548. */
  11549. class NodeMaterial extends Material {
  11550. static get type() {
  11551. return 'NodeMaterial';
  11552. }
  11553. /**
  11554. * Represents the type of the node material.
  11555. *
  11556. * @type {string}
  11557. */
  11558. get type() {
  11559. return this.constructor.type;
  11560. }
  11561. set type( _value ) { /* */ }
  11562. /**
  11563. * Constructs a new node material.
  11564. */
  11565. constructor() {
  11566. super();
  11567. /**
  11568. * This flag can be used for type testing.
  11569. *
  11570. * @type {boolean}
  11571. * @readonly
  11572. * @default true
  11573. */
  11574. this.isNodeMaterial = true;
  11575. /**
  11576. * Whether this material is affected by fog or not.
  11577. *
  11578. * @type {boolean}
  11579. * @default true
  11580. */
  11581. this.fog = true;
  11582. /**
  11583. * Whether this material is affected by lights or not.
  11584. *
  11585. * @type {boolean}
  11586. * @default false
  11587. */
  11588. this.lights = false;
  11589. /**
  11590. * Whether this material uses hardware clipping or not.
  11591. * This property is managed by the engine and should not be
  11592. * modified by apps.
  11593. *
  11594. * @type {boolean}
  11595. * @default false
  11596. */
  11597. this.hardwareClipping = false;
  11598. /**
  11599. * Node materials which set their `lights` property to `true`
  11600. * are affected by all lights of the scene. Sometimes selective
  11601. * lighting is wanted which means only _some_ lights in the scene
  11602. * affect a material. This can be achieved by creating an instance
  11603. * of {@link LightsNode} with a list of selective
  11604. * lights and assign the node to this property.
  11605. *
  11606. * ```js
  11607. * const customLightsNode = lights( [ light1, light2 ] );
  11608. * material.lightsNode = customLightsNode;
  11609. * ```
  11610. *
  11611. * @type {?LightsNode}
  11612. * @default null
  11613. */
  11614. this.lightsNode = null;
  11615. /**
  11616. * The environment of node materials can be defined by an environment
  11617. * map assigned to the `envMap` property or by `Scene.environment`
  11618. * if the node material is a PBR material. This node property allows to overwrite
  11619. * the default behavior and define the environment with a custom node.
  11620. *
  11621. * ```js
  11622. * material.envNode = pmremTexture( renderTarget.texture );
  11623. * ```
  11624. *
  11625. * @type {?Node<vec3>}
  11626. * @default null
  11627. */
  11628. this.envNode = null;
  11629. /**
  11630. * The lighting of node materials might be influenced by ambient occlusion.
  11631. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11632. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11633. * the default and define the ambient occlusion with a custom node instead.
  11634. *
  11635. * If you don't want to overwrite the diffuse color but modify the existing
  11636. * values instead, use {@link materialAO}.
  11637. *
  11638. * @type {?Node<float>}
  11639. * @default null
  11640. */
  11641. this.aoNode = null;
  11642. /**
  11643. * The diffuse color of node materials is by default inferred from the
  11644. * `color` and `map` properties. This node property allows to overwrite the default
  11645. * and define the diffuse color with a node instead.
  11646. *
  11647. * ```js
  11648. * material.colorNode = color( 0xff0000 ); // define red color
  11649. * ```
  11650. *
  11651. * If you don't want to overwrite the diffuse color but modify the existing
  11652. * values instead, use {@link materialColor}.
  11653. *
  11654. * ```js
  11655. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11656. * ```
  11657. *
  11658. * @type {?Node<vec3>}
  11659. * @default null
  11660. */
  11661. this.colorNode = null;
  11662. /**
  11663. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11664. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11665. * and define the normals with a node instead.
  11666. *
  11667. * If you don't want to overwrite the normals but modify the existing values instead,
  11668. * use {@link materialNormal}.
  11669. *
  11670. * @type {?Node<vec3>}
  11671. * @default null
  11672. */
  11673. this.normalNode = null;
  11674. /**
  11675. * The opacity of node materials is by default inferred from the `opacity`
  11676. * and `alphaMap` properties. This node property allows to overwrite the default
  11677. * and define the opacity with a node instead.
  11678. *
  11679. * If you don't want to overwrite the normals but modify the existing
  11680. * value instead, use {@link materialOpacity}.
  11681. *
  11682. * @type {?Node<float>}
  11683. * @default null
  11684. */
  11685. this.opacityNode = null;
  11686. /**
  11687. * This node can be used to to implement a variety of filter-like effects. The idea is
  11688. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11689. * to create an arbitrary effect and then assign the node composition to this property.
  11690. * Everything behind the object using this material will now be affected by a filter.
  11691. *
  11692. * ```js
  11693. * const material = new NodeMaterial()
  11694. * material.transparent = true;
  11695. *
  11696. * // everything behind the object will be monochromatic
  11697. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  11698. * ```
  11699. *
  11700. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11701. *
  11702. * @type {?Node<vec3>}
  11703. * @default null
  11704. */
  11705. this.backdropNode = null;
  11706. /**
  11707. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11708. *
  11709. * @type {?Node<float>}
  11710. * @default null
  11711. */
  11712. this.backdropAlphaNode = null;
  11713. /**
  11714. * The alpha test of node materials is by default inferred from the `alphaTest`
  11715. * property. This node property allows to overwrite the default and define the
  11716. * alpha test with a node instead.
  11717. *
  11718. * If you don't want to overwrite the alpha test but modify the existing
  11719. * value instead, use {@link materialAlphaTest}.
  11720. *
  11721. * @type {?Node<float>}
  11722. * @default null
  11723. */
  11724. this.alphaTestNode = null;
  11725. /**
  11726. * The local vertex positions are computed based on multiple factors like the
  11727. * attribute data, morphing or skinning. This node property allows to overwrite
  11728. * the default and define local vertex positions with nodes instead.
  11729. *
  11730. * If you don't want to overwrite the vertex positions but modify the existing
  11731. * values instead, use {@link positionLocal}.
  11732. *
  11733. *```js
  11734. * material.positionNode = positionLocal.add( displace );
  11735. * ```
  11736. *
  11737. * @type {?Node<vec3>}
  11738. * @default null
  11739. */
  11740. this.positionNode = null;
  11741. /**
  11742. * This node property is intended for logic which modifies geometry data once or per animation step.
  11743. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11744. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11745. * can be implemented.
  11746. *
  11747. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11748. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11749. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11750. * eventually assigned to `geometryNode`.
  11751. *
  11752. * @type {?Function}
  11753. * @default null
  11754. */
  11755. this.geometryNode = null;
  11756. /**
  11757. * Allows to overwrite depth values in the fragment shader.
  11758. *
  11759. * @type {?Node<float>}
  11760. * @default null
  11761. */
  11762. this.depthNode = null;
  11763. /**
  11764. * Allows to overwrite the position used for shadow map rendering which
  11765. * is by default {@link positionWorld}, the vertex position
  11766. * in world space.
  11767. *
  11768. * @type {?Node<float>}
  11769. * @default null
  11770. */
  11771. this.shadowPositionNode = null;
  11772. /**
  11773. * This node can be used to influence how an object using this node material
  11774. * receive shadows.
  11775. *
  11776. * ```js
  11777. * const totalShadows = float( 1 ).toVar();
  11778. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11779. * totalShadows.mulAssign( shadow );
  11780. * //return float( 1 ); // bypass received shadows
  11781. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11782. * } );
  11783. *
  11784. * @type {?(Function|FunctionNode<vec4>)}
  11785. * @default null
  11786. */
  11787. this.receivedShadowNode = null;
  11788. /**
  11789. * This node can be used to influence how an object using this node material
  11790. * casts shadows. To apply a color to shadows, you can simply do:
  11791. *
  11792. * ```js
  11793. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11794. * ```
  11795. *
  11796. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11797. * is also common to use the property with `Fn` function so checks are performed
  11798. * per fragment.
  11799. *
  11800. * ```js
  11801. * materialCustomShadow.castShadowNode = Fn( () => {
  11802. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11803. * return materialColor;
  11804. * } )();
  11805. * ```
  11806. *
  11807. * @type {?Node<vec4>}
  11808. * @default null
  11809. */
  11810. this.castShadowNode = null;
  11811. /**
  11812. * This node can be used to define the final output of the material.
  11813. *
  11814. * TODO: Explain the differences to `fragmentNode`.
  11815. *
  11816. * @type {?Node<vec4>}
  11817. * @default null
  11818. */
  11819. this.outputNode = null;
  11820. /**
  11821. * MRT configuration is done on renderer or pass level. This node allows to
  11822. * overwrite what values are written into MRT targets on material level. This
  11823. * can be useful for implementing selective FX features that should only affect
  11824. * specific objects.
  11825. *
  11826. * @type {?MRTNode}
  11827. * @default null
  11828. */
  11829. this.mrtNode = null;
  11830. /**
  11831. * This node property can be used if you need complete freedom in implementing
  11832. * the fragment shader. Assigning a node will replace the built-in material
  11833. * logic used in the fragment stage.
  11834. *
  11835. * @type {?Node<vec4>}
  11836. * @default null
  11837. */
  11838. this.fragmentNode = null;
  11839. /**
  11840. * This node property can be used if you need complete freedom in implementing
  11841. * the vertex shader. Assigning a node will replace the built-in material logic
  11842. * used in the vertex stage.
  11843. *
  11844. * @type {?Node<vec4>}
  11845. * @default null
  11846. */
  11847. this.vertexNode = null;
  11848. }
  11849. /**
  11850. * Allows to define a custom cache key that influence the material key computation
  11851. * for render objects.
  11852. *
  11853. * @return {string} The custom cache key.
  11854. */
  11855. customProgramCacheKey() {
  11856. return this.type + getCacheKey$1( this );
  11857. }
  11858. /**
  11859. * Builds this material with the given node builder.
  11860. *
  11861. * @param {NodeBuilder} builder - The current node builder.
  11862. */
  11863. build( builder ) {
  11864. this.setup( builder );
  11865. }
  11866. /**
  11867. * Setups a node material observer with the given builder.
  11868. *
  11869. * @param {NodeBuilder} builder - The current node builder.
  11870. * @return {NodeMaterialObserver} The node material observer.
  11871. */
  11872. setupObserver( builder ) {
  11873. return new NodeMaterialObserver( builder );
  11874. }
  11875. /**
  11876. * Setups the vertex and fragment stage of this node material.
  11877. *
  11878. * @param {NodeBuilder} builder - The current node builder.
  11879. */
  11880. setup( builder ) {
  11881. builder.context.setupNormal = () => this.setupNormal( builder );
  11882. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11883. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11884. const renderer = builder.renderer;
  11885. const renderTarget = renderer.getRenderTarget();
  11886. // < VERTEX STAGE >
  11887. builder.addStack();
  11888. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11889. builder.stack.outputNode = vertexNode;
  11890. this.setupHardwareClipping( builder );
  11891. if ( this.geometryNode !== null ) {
  11892. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11893. }
  11894. builder.addFlow( 'vertex', builder.removeStack() );
  11895. // < FRAGMENT STAGE >
  11896. builder.addStack();
  11897. let resultNode;
  11898. const clippingNode = this.setupClipping( builder );
  11899. if ( this.depthWrite === true || this.depthTest === true ) {
  11900. // only write depth if depth buffer is configured
  11901. if ( renderTarget !== null ) {
  11902. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11903. } else {
  11904. if ( renderer.depth === true ) this.setupDepth( builder );
  11905. }
  11906. }
  11907. if ( this.fragmentNode === null ) {
  11908. this.setupDiffuseColor( builder );
  11909. this.setupVariants( builder );
  11910. const outgoingLightNode = this.setupLighting( builder );
  11911. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11912. // force unsigned floats - useful for RenderTargets
  11913. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11914. resultNode = this.setupOutput( builder, basicOutput );
  11915. // OUTPUT NODE
  11916. output.assign( resultNode );
  11917. //
  11918. const isCustomOutput = this.outputNode !== null;
  11919. if ( isCustomOutput ) resultNode = this.outputNode;
  11920. // MRT
  11921. if ( renderTarget !== null ) {
  11922. const mrt = renderer.getMRT();
  11923. const materialMRT = this.mrtNode;
  11924. if ( mrt !== null ) {
  11925. if ( isCustomOutput ) output.assign( resultNode );
  11926. resultNode = mrt;
  11927. if ( materialMRT !== null ) {
  11928. resultNode = mrt.merge( materialMRT );
  11929. }
  11930. } else if ( materialMRT !== null ) {
  11931. resultNode = materialMRT;
  11932. }
  11933. }
  11934. } else {
  11935. let fragmentNode = this.fragmentNode;
  11936. if ( fragmentNode.isOutputStructNode !== true ) {
  11937. fragmentNode = vec4( fragmentNode );
  11938. }
  11939. resultNode = this.setupOutput( builder, fragmentNode );
  11940. }
  11941. builder.stack.outputNode = resultNode;
  11942. builder.addFlow( 'fragment', builder.removeStack() );
  11943. // < OBSERVER >
  11944. builder.observer = this.setupObserver( builder );
  11945. }
  11946. /**
  11947. * Setups the clipping node.
  11948. *
  11949. * @param {NodeBuilder} builder - The current node builder.
  11950. * @return {ClippingNode} The clipping node.
  11951. */
  11952. setupClipping( builder ) {
  11953. if ( builder.clippingContext === null ) return null;
  11954. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11955. let result = null;
  11956. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11957. const samples = builder.renderer.samples;
  11958. if ( this.alphaToCoverage && samples > 1 ) {
  11959. // to be added to flow when the color/alpha value has been determined
  11960. result = clippingAlpha();
  11961. } else {
  11962. builder.stack.add( clipping() );
  11963. }
  11964. }
  11965. return result;
  11966. }
  11967. /**
  11968. * Setups the hardware clipping if available on the current device.
  11969. *
  11970. * @param {NodeBuilder} builder - The current node builder.
  11971. */
  11972. setupHardwareClipping( builder ) {
  11973. this.hardwareClipping = false;
  11974. if ( builder.clippingContext === null ) return;
  11975. const candidateCount = builder.clippingContext.unionPlanes.length;
  11976. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11977. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11978. builder.stack.add( hardwareClipping() );
  11979. this.hardwareClipping = true;
  11980. }
  11981. return;
  11982. }
  11983. /**
  11984. * Setups the depth of this material.
  11985. *
  11986. * @param {NodeBuilder} builder - The current node builder.
  11987. */
  11988. setupDepth( builder ) {
  11989. const { renderer, camera } = builder;
  11990. // Depth
  11991. let depthNode = this.depthNode;
  11992. if ( depthNode === null ) {
  11993. const mrt = renderer.getMRT();
  11994. if ( mrt && mrt.has( 'depth' ) ) {
  11995. depthNode = mrt.get( 'depth' );
  11996. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11997. if ( camera.isPerspectiveCamera ) {
  11998. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11999. } else {
  12000. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12001. }
  12002. }
  12003. }
  12004. if ( depthNode !== null ) {
  12005. depth.assign( depthNode ).append();
  12006. }
  12007. }
  12008. /**
  12009. * Setups the position node in view space. This method exists
  12010. * so derived node materials can modify the implementation e.g. sprite materials.
  12011. *
  12012. * @param {NodeBuilder} builder - The current node builder.
  12013. * @return {Node<vec3>} The position in view space.
  12014. */
  12015. setupPositionView( /*builder*/ ) {
  12016. return modelViewMatrix.mul( positionLocal ).xyz;
  12017. }
  12018. /**
  12019. * Setups the position in clip space.
  12020. *
  12021. * @param {NodeBuilder} builder - The current node builder.
  12022. * @return {Node<vec4>} The position in view space.
  12023. */
  12024. setupModelViewProjection( /*builder*/ ) {
  12025. return cameraProjectionMatrix.mul( positionView );
  12026. }
  12027. /**
  12028. * Setups the logic for the vertex stage.
  12029. *
  12030. * @param {NodeBuilder} builder - The current node builder.
  12031. * @return {Node<vec4>} The position in clip space.
  12032. */
  12033. setupVertex( builder ) {
  12034. builder.addStack();
  12035. this.setupPosition( builder );
  12036. builder.context.vertex = builder.removeStack();
  12037. return modelViewProjection;
  12038. }
  12039. /**
  12040. * Setups the computation of the position in local space.
  12041. *
  12042. * @param {NodeBuilder} builder - The current node builder.
  12043. * @return {Node<vec3>} The position in local space.
  12044. */
  12045. setupPosition( builder ) {
  12046. const { object, geometry } = builder;
  12047. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  12048. morphReference( object ).append();
  12049. }
  12050. if ( object.isSkinnedMesh === true ) {
  12051. skinningReference( object ).append();
  12052. }
  12053. if ( this.displacementMap ) {
  12054. const displacementMap = materialReference( 'displacementMap', 'texture' );
  12055. const displacementScale = materialReference( 'displacementScale', 'float' );
  12056. const displacementBias = materialReference( 'displacementBias', 'float' );
  12057. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  12058. }
  12059. if ( object.isBatchedMesh ) {
  12060. batch( object ).append();
  12061. }
  12062. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  12063. instancedMesh( object ).append();
  12064. }
  12065. if ( this.positionNode !== null ) {
  12066. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  12067. }
  12068. return positionLocal;
  12069. }
  12070. /**
  12071. * Setups the computation of the material's diffuse color.
  12072. *
  12073. * @param {NodeBuilder} builder - The current node builder.
  12074. * @param {BufferGeometry} geometry - The geometry.
  12075. */
  12076. setupDiffuseColor( { object, geometry } ) {
  12077. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  12078. // VERTEX COLORS
  12079. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  12080. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  12081. }
  12082. // Instanced colors
  12083. if ( object.instanceColor ) {
  12084. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  12085. colorNode = instanceColor.mul( colorNode );
  12086. }
  12087. if ( object.isBatchedMesh && object._colorsTexture ) {
  12088. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  12089. colorNode = batchColor.mul( colorNode );
  12090. }
  12091. // COLOR
  12092. diffuseColor.assign( colorNode );
  12093. // OPACITY
  12094. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12095. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  12096. // ALPHA TEST
  12097. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  12098. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  12099. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  12100. }
  12101. // ALPHA HASH
  12102. if ( this.alphaHash === true ) {
  12103. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  12104. }
  12105. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  12106. diffuseColor.a.assign( 1.0 );
  12107. }
  12108. }
  12109. /**
  12110. * Abstract interface method that can be implemented by derived materials
  12111. * to setup material-specific node variables.
  12112. *
  12113. * @abstract
  12114. * @param {NodeBuilder} builder - The current node builder.
  12115. */
  12116. setupVariants( /*builder*/ ) {
  12117. // Interface function.
  12118. }
  12119. /**
  12120. * Setups the outgoing light node variable
  12121. *
  12122. * @return {Node<vec3>} The outgoing light node.
  12123. */
  12124. setupOutgoingLight() {
  12125. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  12126. }
  12127. /**
  12128. * Setups the normal node from the material.
  12129. *
  12130. * @return {Node<vec3>} The normal node.
  12131. */
  12132. setupNormal() {
  12133. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  12134. }
  12135. /**
  12136. * Setups the environment node from the material.
  12137. *
  12138. * @param {NodeBuilder} builder - The current node builder.
  12139. * @return {Node<vec4>} The environment node.
  12140. */
  12141. setupEnvironment( /*builder*/ ) {
  12142. let node = null;
  12143. if ( this.envNode ) {
  12144. node = this.envNode;
  12145. } else if ( this.envMap ) {
  12146. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  12147. }
  12148. return node;
  12149. }
  12150. /**
  12151. * Setups the light map node from the material.
  12152. *
  12153. * @param {NodeBuilder} builder - The current node builder.
  12154. * @return {Node<vec3>} The light map node.
  12155. */
  12156. setupLightMap( builder ) {
  12157. let node = null;
  12158. if ( builder.material.lightMap ) {
  12159. node = new IrradianceNode( materialLightMap );
  12160. }
  12161. return node;
  12162. }
  12163. /**
  12164. * Setups the lights node based on the scene, environment and material.
  12165. *
  12166. * @param {NodeBuilder} builder - The current node builder.
  12167. * @return {LightsNode} The lights node.
  12168. */
  12169. setupLights( builder ) {
  12170. const materialLightsNode = [];
  12171. //
  12172. const envNode = this.setupEnvironment( builder );
  12173. if ( envNode && envNode.isLightingNode ) {
  12174. materialLightsNode.push( envNode );
  12175. }
  12176. const lightMapNode = this.setupLightMap( builder );
  12177. if ( lightMapNode && lightMapNode.isLightingNode ) {
  12178. materialLightsNode.push( lightMapNode );
  12179. }
  12180. if ( this.aoNode !== null || builder.material.aoMap ) {
  12181. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  12182. materialLightsNode.push( new AONode( aoNode ) );
  12183. }
  12184. let lightsN = this.lightsNode || builder.lightsNode;
  12185. if ( materialLightsNode.length > 0 ) {
  12186. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  12187. }
  12188. return lightsN;
  12189. }
  12190. /**
  12191. * This method should be implemented by most derived materials
  12192. * since it defines the material's lighting model.
  12193. *
  12194. * @abstract
  12195. * @param {NodeBuilder} builder - The current node builder.
  12196. * @return {LightingModel} The lighting model.
  12197. */
  12198. setupLightingModel( /*builder*/ ) {
  12199. // Interface function.
  12200. }
  12201. /**
  12202. * Setups the outgoing light node.
  12203. *
  12204. * @param {NodeBuilder} builder - The current node builder.
  12205. * @return {Node<vec3>} The outgoing light node.
  12206. */
  12207. setupLighting( builder ) {
  12208. const { material } = builder;
  12209. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  12210. // OUTGOING LIGHT
  12211. const lights = this.lights === true || this.lightsNode !== null;
  12212. const lightsNode = lights ? this.setupLights( builder ) : null;
  12213. let outgoingLightNode = this.setupOutgoingLight( builder );
  12214. if ( lightsNode && lightsNode.getScope().hasLights ) {
  12215. const lightingModel = this.setupLightingModel( builder ) || null;
  12216. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  12217. } else if ( backdropNode !== null ) {
  12218. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  12219. }
  12220. // EMISSIVE
  12221. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  12222. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  12223. outgoingLightNode = outgoingLightNode.add( emissive );
  12224. }
  12225. return outgoingLightNode;
  12226. }
  12227. /**
  12228. * Setup the fog.
  12229. *
  12230. * @param {NodeBuilder} builder - The current node builder.
  12231. * @param {Node<vec4>} outputNode - The existing output node.
  12232. * @return {Node<vec4>} The output node.
  12233. */
  12234. setupFog( builder, outputNode ) {
  12235. const fogNode = builder.fogNode;
  12236. if ( fogNode ) {
  12237. output.assign( outputNode );
  12238. outputNode = vec4( fogNode );
  12239. }
  12240. return outputNode;
  12241. }
  12242. /**
  12243. * Setups the output node.
  12244. *
  12245. * @param {NodeBuilder} builder - The current node builder.
  12246. * @param {Node<vec4>} outputNode - The existing output node.
  12247. * @return {Node<vec4>} The output node.
  12248. */
  12249. setupOutput( builder, outputNode ) {
  12250. // FOG
  12251. if ( this.fog === true ) {
  12252. outputNode = this.setupFog( builder, outputNode );
  12253. }
  12254. return outputNode;
  12255. }
  12256. /**
  12257. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  12258. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  12259. * defining all material properties of the classic type in the node type.
  12260. *
  12261. * @param {Material} material - The material to copy properties with their values to this node material.
  12262. */
  12263. setDefaultValues( material ) {
  12264. // This approach is to reuse the native refreshUniforms*
  12265. // and turn available the use of features like transmission and environment in core
  12266. for ( const property in material ) {
  12267. const value = material[ property ];
  12268. if ( this[ property ] === undefined ) {
  12269. this[ property ] = value;
  12270. if ( value && value.clone ) this[ property ] = value.clone();
  12271. }
  12272. }
  12273. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  12274. for ( const key in descriptors ) {
  12275. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  12276. descriptors[ key ].get !== undefined ) {
  12277. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  12278. }
  12279. }
  12280. }
  12281. /**
  12282. * Serializes this material to JSON.
  12283. *
  12284. * @param {?(Object|string)} meta - The meta information for serialization.
  12285. * @return {Object} The serialized node.
  12286. */
  12287. toJSON( meta ) {
  12288. const isRoot = ( meta === undefined || typeof meta === 'string' );
  12289. if ( isRoot ) {
  12290. meta = {
  12291. textures: {},
  12292. images: {},
  12293. nodes: {}
  12294. };
  12295. }
  12296. const data = Material.prototype.toJSON.call( this, meta );
  12297. const nodeChildren = getNodeChildren( this );
  12298. data.inputNodes = {};
  12299. for ( const { property, childNode } of nodeChildren ) {
  12300. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  12301. }
  12302. // TODO: Copied from Object3D.toJSON
  12303. function extractFromCache( cache ) {
  12304. const values = [];
  12305. for ( const key in cache ) {
  12306. const data = cache[ key ];
  12307. delete data.metadata;
  12308. values.push( data );
  12309. }
  12310. return values;
  12311. }
  12312. if ( isRoot ) {
  12313. const textures = extractFromCache( meta.textures );
  12314. const images = extractFromCache( meta.images );
  12315. const nodes = extractFromCache( meta.nodes );
  12316. if ( textures.length > 0 ) data.textures = textures;
  12317. if ( images.length > 0 ) data.images = images;
  12318. if ( nodes.length > 0 ) data.nodes = nodes;
  12319. }
  12320. return data;
  12321. }
  12322. /**
  12323. * Copies the properties of the given node material to this instance.
  12324. *
  12325. * @param {NodeMaterial} source - The material to copy.
  12326. * @return {NodeMaterial} A reference to this node material.
  12327. */
  12328. copy( source ) {
  12329. this.lightsNode = source.lightsNode;
  12330. this.envNode = source.envNode;
  12331. this.colorNode = source.colorNode;
  12332. this.normalNode = source.normalNode;
  12333. this.opacityNode = source.opacityNode;
  12334. this.backdropNode = source.backdropNode;
  12335. this.backdropAlphaNode = source.backdropAlphaNode;
  12336. this.alphaTestNode = source.alphaTestNode;
  12337. this.positionNode = source.positionNode;
  12338. this.geometryNode = source.geometryNode;
  12339. this.depthNode = source.depthNode;
  12340. this.shadowPositionNode = source.shadowPositionNode;
  12341. this.receivedShadowNode = source.receivedShadowNode;
  12342. this.castShadowNode = source.castShadowNode;
  12343. this.outputNode = source.outputNode;
  12344. this.mrtNode = source.mrtNode;
  12345. this.fragmentNode = source.fragmentNode;
  12346. this.vertexNode = source.vertexNode;
  12347. return super.copy( source );
  12348. }
  12349. }
  12350. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  12351. /**
  12352. * Node material version of {@link LineBasicMaterial}.
  12353. *
  12354. * @augments NodeMaterial
  12355. */
  12356. class LineBasicNodeMaterial extends NodeMaterial {
  12357. static get type() {
  12358. return 'LineBasicNodeMaterial';
  12359. }
  12360. /**
  12361. * Constructs a new line basic node material.
  12362. *
  12363. * @param {Object} [parameters] - The configuration parameter.
  12364. */
  12365. constructor( parameters ) {
  12366. super();
  12367. /**
  12368. * This flag can be used for type testing.
  12369. *
  12370. * @type {boolean}
  12371. * @readonly
  12372. * @default true
  12373. */
  12374. this.isLineBasicNodeMaterial = true;
  12375. this.setDefaultValues( _defaultValues$d );
  12376. this.setValues( parameters );
  12377. }
  12378. }
  12379. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  12380. /**
  12381. * Node material version of {@link LineDashedMaterial}.
  12382. *
  12383. * @augments NodeMaterial
  12384. */
  12385. class LineDashedNodeMaterial extends NodeMaterial {
  12386. static get type() {
  12387. return 'LineDashedNodeMaterial';
  12388. }
  12389. /**
  12390. * Constructs a new line dashed node material.
  12391. *
  12392. * @param {Object} [parameters] - The configuration parameter.
  12393. */
  12394. constructor( parameters ) {
  12395. super();
  12396. /**
  12397. * This flag can be used for type testing.
  12398. *
  12399. * @type {boolean}
  12400. * @readonly
  12401. * @default true
  12402. */
  12403. this.isLineDashedNodeMaterial = true;
  12404. this.setDefaultValues( _defaultValues$c );
  12405. /**
  12406. * The dash offset.
  12407. *
  12408. * @type {number}
  12409. * @default 0
  12410. */
  12411. this.dashOffset = 0;
  12412. /**
  12413. * The offset of dash materials is by default inferred from the `dashOffset`
  12414. * property. This node property allows to overwrite the default
  12415. * and define the offset with a node instead.
  12416. *
  12417. * If you don't want to overwrite the offset but modify the existing
  12418. * value instead, use {@link materialLineDashOffset}.
  12419. *
  12420. * @type {?Node<float>}
  12421. * @default null
  12422. */
  12423. this.offsetNode = null;
  12424. /**
  12425. * The scale of dash materials is by default inferred from the `scale`
  12426. * property. This node property allows to overwrite the default
  12427. * and define the scale with a node instead.
  12428. *
  12429. * If you don't want to overwrite the scale but modify the existing
  12430. * value instead, use {@link materialLineScale}.
  12431. *
  12432. * @type {?Node<float>}
  12433. * @default null
  12434. */
  12435. this.dashScaleNode = null;
  12436. /**
  12437. * The dash size of dash materials is by default inferred from the `dashSize`
  12438. * property. This node property allows to overwrite the default
  12439. * and define the dash size with a node instead.
  12440. *
  12441. * If you don't want to overwrite the dash size but modify the existing
  12442. * value instead, use {@link materialLineDashSize}.
  12443. *
  12444. * @type {?Node<float>}
  12445. * @default null
  12446. */
  12447. this.dashSizeNode = null;
  12448. /**
  12449. * The gap size of dash materials is by default inferred from the `gapSize`
  12450. * property. This node property allows to overwrite the default
  12451. * and define the gap size with a node instead.
  12452. *
  12453. * If you don't want to overwrite the gap size but modify the existing
  12454. * value instead, use {@link materialLineGapSize}.
  12455. *
  12456. * @type {?Node<float>}
  12457. * @default null
  12458. */
  12459. this.gapSizeNode = null;
  12460. this.setValues( parameters );
  12461. }
  12462. /**
  12463. * Setups the dash specific node variables.
  12464. *
  12465. * @param {NodeBuilder} builder - The current node builder.
  12466. */
  12467. setupVariants( /* builder */ ) {
  12468. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12469. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12470. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12471. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12472. dashSize.assign( dashSizeNode );
  12473. gapSize.assign( gapSizeNode );
  12474. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  12475. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  12476. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  12477. }
  12478. }
  12479. let _sharedFramebuffer = null;
  12480. /**
  12481. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  12482. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  12483. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  12484. *
  12485. * @augments ViewportTextureNode
  12486. */
  12487. class ViewportSharedTextureNode extends ViewportTextureNode {
  12488. static get type() {
  12489. return 'ViewportSharedTextureNode';
  12490. }
  12491. /**
  12492. * Constructs a new viewport shared texture node.
  12493. *
  12494. * @param {Node} [uvNode=screenUV] - The uv node.
  12495. * @param {?Node} [levelNode=null] - The level node.
  12496. */
  12497. constructor( uvNode = screenUV, levelNode = null ) {
  12498. if ( _sharedFramebuffer === null ) {
  12499. _sharedFramebuffer = new FramebufferTexture();
  12500. }
  12501. super( uvNode, levelNode, _sharedFramebuffer );
  12502. }
  12503. updateReference() {
  12504. return this;
  12505. }
  12506. }
  12507. /**
  12508. * TSL function for creating a shared viewport texture node.
  12509. *
  12510. * @tsl
  12511. * @function
  12512. * @param {Node} [uvNode=screenUV] - The uv node.
  12513. * @param {?Node} [levelNode=null] - The level node.
  12514. * @returns {ViewportSharedTextureNode}
  12515. */
  12516. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  12517. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  12518. /**
  12519. * This node material can be used to render lines with a size larger than one
  12520. * by representing them as instanced meshes.
  12521. *
  12522. * @augments NodeMaterial
  12523. */
  12524. class Line2NodeMaterial extends NodeMaterial {
  12525. static get type() {
  12526. return 'Line2NodeMaterial';
  12527. }
  12528. /**
  12529. * Constructs a new node material for wide line rendering.
  12530. *
  12531. * @param {Object} [parameters={}] - The configuration parameter.
  12532. */
  12533. constructor( parameters = {} ) {
  12534. super();
  12535. /**
  12536. * This flag can be used for type testing.
  12537. *
  12538. * @type {boolean}
  12539. * @readonly
  12540. * @default true
  12541. */
  12542. this.isLine2NodeMaterial = true;
  12543. this.setDefaultValues( _defaultValues$b );
  12544. /**
  12545. * Whether vertex colors should be used or not.
  12546. *
  12547. * @type {boolean}
  12548. * @default false
  12549. */
  12550. this.useColor = parameters.vertexColors;
  12551. /**
  12552. * The dash offset.
  12553. *
  12554. * @type {number}
  12555. * @default 0
  12556. */
  12557. this.dashOffset = 0;
  12558. /**
  12559. * The line width.
  12560. *
  12561. * @type {number}
  12562. * @default 0
  12563. */
  12564. this.lineWidth = 1;
  12565. /**
  12566. * Defines the lines color.
  12567. *
  12568. * @type {?Node<vec3>}
  12569. * @default null
  12570. */
  12571. this.lineColorNode = null;
  12572. /**
  12573. * Defines the offset.
  12574. *
  12575. * @type {?Node<float>}
  12576. * @default null
  12577. */
  12578. this.offsetNode = null;
  12579. /**
  12580. * Defines the dash scale.
  12581. *
  12582. * @type {?Node<float>}
  12583. * @default null
  12584. */
  12585. this.dashScaleNode = null;
  12586. /**
  12587. * Defines the dash size.
  12588. *
  12589. * @type {?Node<float>}
  12590. * @default null
  12591. */
  12592. this.dashSizeNode = null;
  12593. /**
  12594. * Defines the gap size.
  12595. *
  12596. * @type {?Node<float>}
  12597. * @default null
  12598. */
  12599. this.gapSizeNode = null;
  12600. /**
  12601. * Blending is set to `NoBlending` since transparency
  12602. * is not supported, yet.
  12603. *
  12604. * @type {number}
  12605. * @default 0
  12606. */
  12607. this.blending = NoBlending;
  12608. this._useDash = parameters.dashed;
  12609. this._useAlphaToCoverage = true;
  12610. this._useWorldUnits = false;
  12611. this.setValues( parameters );
  12612. }
  12613. /**
  12614. * Setups the vertex and fragment stage of this node material.
  12615. *
  12616. * @param {NodeBuilder} builder - The current node builder.
  12617. */
  12618. setup( builder ) {
  12619. const { renderer } = builder;
  12620. const useAlphaToCoverage = this._useAlphaToCoverage;
  12621. const useColor = this.useColor;
  12622. const useDash = this._useDash;
  12623. const useWorldUnits = this._useWorldUnits;
  12624. const trimSegment = Fn( ( { start, end } ) => {
  12625. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12626. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12627. const nearEstimate = b.mul( -0.5 ).div( a );
  12628. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12629. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12630. } ).setLayout( {
  12631. name: 'trimSegment',
  12632. type: 'vec4',
  12633. inputs: [
  12634. { name: 'start', type: 'vec4' },
  12635. { name: 'end', type: 'vec4' }
  12636. ]
  12637. } );
  12638. this.vertexNode = Fn( () => {
  12639. const instanceStart = attribute( 'instanceStart' );
  12640. const instanceEnd = attribute( 'instanceEnd' );
  12641. // camera space
  12642. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12643. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12644. if ( useDash ) {
  12645. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12646. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12647. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12648. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12649. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12650. lineDistance = lineDistance.add( offsetNode );
  12651. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12652. }
  12653. if ( useWorldUnits ) {
  12654. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12655. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12656. }
  12657. const aspect = viewport.z.div( viewport.w );
  12658. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12659. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12660. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12661. // perhaps there is a more elegant solution -- WestLangley
  12662. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  12663. If( perspective, () => {
  12664. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12665. end.assign( trimSegment( { start: start, end: end } ) );
  12666. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12667. start.assign( trimSegment( { start: end, end: start } ) );
  12668. } );
  12669. } );
  12670. // clip space
  12671. const clipStart = cameraProjectionMatrix.mul( start );
  12672. const clipEnd = cameraProjectionMatrix.mul( end );
  12673. // ndc space
  12674. const ndcStart = clipStart.xyz.div( clipStart.w );
  12675. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12676. // direction
  12677. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12678. // account for clip-space aspect ratio
  12679. dir.x.assign( dir.x.mul( aspect ) );
  12680. dir.assign( dir.normalize() );
  12681. const clip = vec4().toVar();
  12682. if ( useWorldUnits ) {
  12683. // get the offset direction as perpendicular to the view vector
  12684. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12685. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12686. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12687. const worldFwd = worldDir.cross( worldUp );
  12688. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12689. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12690. // height offset
  12691. const hw = materialLineWidth.mul( 0.5 );
  12692. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12693. // don't extend the line if we're rendering dashes because we
  12694. // won't be rendering the endcaps
  12695. if ( ! useDash ) {
  12696. // cap extension
  12697. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12698. // add width to the box
  12699. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12700. // endcaps
  12701. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12702. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12703. } );
  12704. }
  12705. // project the worldpos
  12706. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12707. // shift the depth of the projected points so the line
  12708. // segments overlap neatly
  12709. const clipPose = vec3().toVar();
  12710. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12711. clip.z.assign( clipPose.z.mul( clip.w ) );
  12712. } else {
  12713. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12714. // undo aspect ratio adjustment
  12715. dir.x.assign( dir.x.div( aspect ) );
  12716. offset.x.assign( offset.x.div( aspect ) );
  12717. // sign flip
  12718. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12719. // endcaps
  12720. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12721. offset.assign( offset.sub( dir ) );
  12722. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12723. offset.assign( offset.add( dir ) );
  12724. } );
  12725. // adjust for linewidth
  12726. offset.assign( offset.mul( materialLineWidth ) );
  12727. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12728. offset.assign( offset.div( viewport.w ) );
  12729. // select end
  12730. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12731. // back to clip space
  12732. offset.assign( offset.mul( clip.w ) );
  12733. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12734. }
  12735. return clip;
  12736. } )();
  12737. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12738. const p13 = p1.sub( p3 );
  12739. const p43 = p4.sub( p3 );
  12740. const p21 = p2.sub( p1 );
  12741. const d1343 = p13.dot( p43 );
  12742. const d4321 = p43.dot( p21 );
  12743. const d1321 = p13.dot( p21 );
  12744. const d4343 = p43.dot( p43 );
  12745. const d2121 = p21.dot( p21 );
  12746. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12747. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12748. const mua = numer.div( denom ).clamp();
  12749. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12750. return vec2( mua, mub );
  12751. } );
  12752. this.colorNode = Fn( () => {
  12753. const vUv = uv();
  12754. if ( useDash ) {
  12755. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12756. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12757. dashSize.assign( dashSizeNode );
  12758. gapSize.assign( gapSizeNode );
  12759. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12760. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12761. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12762. }
  12763. const alpha = float( 1 ).toVar( 'alpha' );
  12764. if ( useWorldUnits ) {
  12765. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12766. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12767. // Find the closest points on the view ray and the line segment
  12768. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12769. const lineDir = worldEnd.sub( worldStart );
  12770. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12771. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12772. const p2 = rayEnd.mul( params.y );
  12773. const delta = p1.sub( p2 );
  12774. const len = delta.length();
  12775. const norm = len.div( materialLineWidth );
  12776. if ( ! useDash ) {
  12777. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12778. const dnorm = norm.fwidth();
  12779. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12780. } else {
  12781. norm.greaterThan( 0.5 ).discard();
  12782. }
  12783. }
  12784. } else {
  12785. // round endcaps
  12786. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12787. const a = vUv.x;
  12788. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12789. const len2 = a.mul( a ).add( b.mul( b ) );
  12790. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12791. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12792. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12793. } );
  12794. } else {
  12795. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12796. const a = vUv.x;
  12797. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12798. const len2 = a.mul( a ).add( b.mul( b ) );
  12799. len2.greaterThan( 1.0 ).discard();
  12800. } );
  12801. }
  12802. }
  12803. let lineColorNode;
  12804. if ( this.lineColorNode ) {
  12805. lineColorNode = this.lineColorNode;
  12806. } else {
  12807. if ( useColor ) {
  12808. const instanceColorStart = attribute( 'instanceColorStart' );
  12809. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12810. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12811. lineColorNode = instanceColor.mul( materialColor );
  12812. } else {
  12813. lineColorNode = materialColor;
  12814. }
  12815. }
  12816. return vec4( lineColorNode, alpha );
  12817. } )();
  12818. if ( this.transparent ) {
  12819. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12820. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12821. }
  12822. super.setup( builder );
  12823. }
  12824. /**
  12825. * Whether the lines should sized in world units or not.
  12826. * When set to `false` the unit is pixel.
  12827. *
  12828. * @type {boolean}
  12829. * @default false
  12830. */
  12831. get worldUnits() {
  12832. return this._useWorldUnits;
  12833. }
  12834. set worldUnits( value ) {
  12835. if ( this._useWorldUnits !== value ) {
  12836. this._useWorldUnits = value;
  12837. this.needsUpdate = true;
  12838. }
  12839. }
  12840. /**
  12841. * Whether the lines should be dashed or not.
  12842. *
  12843. * @type {boolean}
  12844. * @default false
  12845. */
  12846. get dashed() {
  12847. return this._useDash;
  12848. }
  12849. set dashed( value ) {
  12850. if ( this._useDash !== value ) {
  12851. this._useDash = value;
  12852. this.needsUpdate = true;
  12853. }
  12854. }
  12855. /**
  12856. * Whether alpha to coverage should be used or not.
  12857. *
  12858. * @type {boolean}
  12859. * @default true
  12860. */
  12861. get alphaToCoverage() {
  12862. return this._useAlphaToCoverage;
  12863. }
  12864. set alphaToCoverage( value ) {
  12865. if ( this._useAlphaToCoverage !== value ) {
  12866. this._useAlphaToCoverage = value;
  12867. this.needsUpdate = true;
  12868. }
  12869. }
  12870. }
  12871. /**
  12872. * Packs a direction vector into a color value.
  12873. *
  12874. * @tsl
  12875. * @function
  12876. * @param {Node<vec3>} node - The direction to pack.
  12877. * @return {Node<vec3>} The color.
  12878. */
  12879. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12880. /**
  12881. * Unpacks a color value into a direction vector.
  12882. *
  12883. * @tsl
  12884. * @function
  12885. * @param {Node<vec3>} node - The color to unpack.
  12886. * @return {Node<vec3>} The direction.
  12887. */
  12888. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12889. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12890. /**
  12891. * Node material version of {@link MeshNormalMaterial}.
  12892. *
  12893. * @augments NodeMaterial
  12894. */
  12895. class MeshNormalNodeMaterial extends NodeMaterial {
  12896. static get type() {
  12897. return 'MeshNormalNodeMaterial';
  12898. }
  12899. /**
  12900. * Constructs a new mesh normal node material.
  12901. *
  12902. * @param {Object} [parameters] - The configuration parameter.
  12903. */
  12904. constructor( parameters ) {
  12905. super();
  12906. /**
  12907. * This flag can be used for type testing.
  12908. *
  12909. * @type {boolean}
  12910. * @readonly
  12911. * @default true
  12912. */
  12913. this.isMeshNormalNodeMaterial = true;
  12914. this.setDefaultValues( _defaultValues$a );
  12915. this.setValues( parameters );
  12916. }
  12917. /**
  12918. * Overwrites the default implementation by computing the diffuse color
  12919. * based on the normal data.
  12920. */
  12921. setupDiffuseColor() {
  12922. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12923. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  12924. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( transformedNormalView ), opacityNode ), SRGBColorSpace ) );
  12925. }
  12926. }
  12927. /**
  12928. * Can be used to compute texture coordinates for projecting an
  12929. * equirectangular texture onto a mesh for using it as the scene's
  12930. * background.
  12931. *
  12932. * ```js
  12933. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12934. * ```
  12935. *
  12936. * @augments TempNode
  12937. */
  12938. class EquirectUVNode extends TempNode {
  12939. static get type() {
  12940. return 'EquirectUVNode';
  12941. }
  12942. /**
  12943. * Constructs a new equirect uv node.
  12944. *
  12945. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12946. */
  12947. constructor( dirNode = positionWorldDirection ) {
  12948. super( 'vec2' );
  12949. /**
  12950. * A direction vector for sampling why is by default `positionWorldDirection`.
  12951. *
  12952. * @type {Node<vec3>}
  12953. */
  12954. this.dirNode = dirNode;
  12955. }
  12956. setup() {
  12957. const dir = this.dirNode;
  12958. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12959. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12960. return vec2( u, v );
  12961. }
  12962. }
  12963. /**
  12964. * TSL function for creating an equirect uv node.
  12965. *
  12966. * @tsl
  12967. * @function
  12968. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12969. * @returns {EquirectUVNode}
  12970. */
  12971. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12972. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12973. /**
  12974. * This class represents a cube render target. It is a special version
  12975. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12976. *
  12977. * @augments WebGLCubeRenderTarget
  12978. */
  12979. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12980. /**
  12981. * Constructs a new cube render target.
  12982. *
  12983. * @param {number} [size=1] - The size of the render target.
  12984. * @param {RenderTarget~Options} [options] - The configuration object.
  12985. */
  12986. constructor( size = 1, options = {} ) {
  12987. super( size, options );
  12988. /**
  12989. * This flag can be used for type testing.
  12990. *
  12991. * @type {boolean}
  12992. * @readonly
  12993. * @default true
  12994. */
  12995. this.isCubeRenderTarget = true;
  12996. }
  12997. /**
  12998. * Converts the given equirectangular texture to a cube map.
  12999. *
  13000. * @param {Renderer} renderer - The renderer.
  13001. * @param {Texture} texture - The equirectangular texture.
  13002. * @return {CubeRenderTarget} A reference to this cube render target.
  13003. */
  13004. fromEquirectangularTexture( renderer, texture$1 ) {
  13005. const currentMinFilter = texture$1.minFilter;
  13006. const currentGenerateMipmaps = texture$1.generateMipmaps;
  13007. texture$1.generateMipmaps = true;
  13008. this.texture.type = texture$1.type;
  13009. this.texture.colorSpace = texture$1.colorSpace;
  13010. this.texture.generateMipmaps = texture$1.generateMipmaps;
  13011. this.texture.minFilter = texture$1.minFilter;
  13012. this.texture.magFilter = texture$1.magFilter;
  13013. const geometry = new BoxGeometry( 5, 5, 5 );
  13014. const uvNode = equirectUV( positionWorldDirection );
  13015. const material = new NodeMaterial();
  13016. material.colorNode = texture( texture$1, uvNode, 0 );
  13017. material.side = BackSide;
  13018. material.blending = NoBlending;
  13019. const mesh = new Mesh( geometry, material );
  13020. const scene = new Scene();
  13021. scene.add( mesh );
  13022. // Avoid blurred poles
  13023. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  13024. const camera = new CubeCamera( 1, 10, this );
  13025. const currentMRT = renderer.getMRT();
  13026. renderer.setMRT( null );
  13027. camera.update( renderer, scene );
  13028. renderer.setMRT( currentMRT );
  13029. texture$1.minFilter = currentMinFilter;
  13030. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  13031. mesh.geometry.dispose();
  13032. mesh.material.dispose();
  13033. return this;
  13034. }
  13035. }
  13036. const _cache$1 = new WeakMap();
  13037. /**
  13038. * This node can be used to automatically convert environment maps in the
  13039. * equirectangular format into the cube map format.
  13040. *
  13041. * @augments TempNode
  13042. */
  13043. class CubeMapNode extends TempNode {
  13044. static get type() {
  13045. return 'CubeMapNode';
  13046. }
  13047. /**
  13048. * Constructs a new cube map node.
  13049. *
  13050. * @param {Node} envNode - The node representing the environment map.
  13051. */
  13052. constructor( envNode ) {
  13053. super( 'vec3' );
  13054. /**
  13055. * The node representing the environment map.
  13056. *
  13057. * @type {Node}
  13058. */
  13059. this.envNode = envNode;
  13060. /**
  13061. * A reference to the internal cube texture.
  13062. *
  13063. * @private
  13064. * @type {?CubeTexture}
  13065. * @default null
  13066. */
  13067. this._cubeTexture = null;
  13068. /**
  13069. * A reference to the internal cube texture node.
  13070. *
  13071. * @private
  13072. * @type {CubeTextureNode}
  13073. */
  13074. this._cubeTextureNode = cubeTexture();
  13075. const defaultTexture = new CubeTexture();
  13076. defaultTexture.isRenderTargetTexture = true;
  13077. /**
  13078. * A default cube texture that acts as a placeholder.
  13079. * It is used when the conversion from equirectangular to cube
  13080. * map has not finished yet for a given texture.
  13081. *
  13082. * @private
  13083. * @type {CubeTexture}
  13084. */
  13085. this._defaultTexture = defaultTexture;
  13086. /**
  13087. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  13088. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  13089. *
  13090. * @type {string}
  13091. * @default 'render'
  13092. */
  13093. this.updateBeforeType = NodeUpdateType.RENDER;
  13094. }
  13095. updateBefore( frame ) {
  13096. const { renderer, material } = frame;
  13097. const envNode = this.envNode;
  13098. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  13099. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  13100. if ( texture && texture.isTexture ) {
  13101. const mapping = texture.mapping;
  13102. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  13103. // check for converted cubemap map
  13104. if ( _cache$1.has( texture ) ) {
  13105. const cubeMap = _cache$1.get( texture );
  13106. mapTextureMapping( cubeMap, texture.mapping );
  13107. this._cubeTexture = cubeMap;
  13108. } else {
  13109. // create cube map from equirectangular map
  13110. const image = texture.image;
  13111. if ( isEquirectangularMapReady$1( image ) ) {
  13112. const renderTarget = new CubeRenderTarget( image.height );
  13113. renderTarget.fromEquirectangularTexture( renderer, texture );
  13114. mapTextureMapping( renderTarget.texture, texture.mapping );
  13115. this._cubeTexture = renderTarget.texture;
  13116. _cache$1.set( texture, renderTarget.texture );
  13117. texture.addEventListener( 'dispose', onTextureDispose );
  13118. } else {
  13119. // default cube texture as fallback when equirectangular texture is not yet loaded
  13120. this._cubeTexture = this._defaultTexture;
  13121. }
  13122. }
  13123. //
  13124. this._cubeTextureNode.value = this._cubeTexture;
  13125. } else {
  13126. // envNode already refers to a cube map
  13127. this._cubeTextureNode = this.envNode;
  13128. }
  13129. }
  13130. }
  13131. }
  13132. setup( builder ) {
  13133. this.updateBefore( builder );
  13134. return this._cubeTextureNode;
  13135. }
  13136. }
  13137. /**
  13138. * Returns true if the given equirectangular image has been fully loaded
  13139. * and is ready for further processing.
  13140. *
  13141. * @private
  13142. * @param {Image} image - The equirectangular image to check.
  13143. * @return {boolean} Whether the image is ready or not.
  13144. */
  13145. function isEquirectangularMapReady$1( image ) {
  13146. if ( image === null || image === undefined ) return false;
  13147. return image.height > 0;
  13148. }
  13149. /**
  13150. * This function is executed when `dispose()` is called on the equirectangular
  13151. * texture. In this case, the generated cube map with its render target
  13152. * is deleted as well.
  13153. *
  13154. * @private
  13155. * @param {Object} event - The event object.
  13156. */
  13157. function onTextureDispose( event ) {
  13158. const texture = event.target;
  13159. texture.removeEventListener( 'dispose', onTextureDispose );
  13160. const renderTarget = _cache$1.get( texture );
  13161. if ( renderTarget !== undefined ) {
  13162. _cache$1.delete( texture );
  13163. renderTarget.dispose();
  13164. }
  13165. }
  13166. /**
  13167. * This function makes sure the generated cube map uses the correct
  13168. * texture mapping that corresponds to the equirectangular original.
  13169. *
  13170. * @private
  13171. * @param {Texture} texture - The cube texture.
  13172. * @param {number} mapping - The original texture mapping.
  13173. */
  13174. function mapTextureMapping( texture, mapping ) {
  13175. if ( mapping === EquirectangularReflectionMapping ) {
  13176. texture.mapping = CubeReflectionMapping;
  13177. } else if ( mapping === EquirectangularRefractionMapping ) {
  13178. texture.mapping = CubeRefractionMapping;
  13179. }
  13180. }
  13181. /**
  13182. * TSL function for creating a cube map node.
  13183. *
  13184. * @tsl
  13185. * @function
  13186. * @param {Node} envNode - The node representing the environment map.
  13187. * @returns {CubeMapNode}
  13188. */
  13189. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  13190. /**
  13191. * Represents a basic model for Image-based lighting (IBL). The environment
  13192. * is defined via environment maps in the equirectangular or cube map format.
  13193. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  13194. * or {@link MeshPhongNodeMaterial}.
  13195. *
  13196. * @augments LightingNode
  13197. */
  13198. class BasicEnvironmentNode extends LightingNode {
  13199. static get type() {
  13200. return 'BasicEnvironmentNode';
  13201. }
  13202. /**
  13203. * Constructs a new basic environment node.
  13204. *
  13205. * @param {Node} [envNode=null] - A node representing the environment.
  13206. */
  13207. constructor( envNode = null ) {
  13208. super();
  13209. /**
  13210. * A node representing the environment.
  13211. *
  13212. * @type {Node}
  13213. * @default null
  13214. */
  13215. this.envNode = envNode;
  13216. }
  13217. setup( builder ) {
  13218. // environment property is used in the finish() method of BasicLightingModel
  13219. builder.context.environment = cubeMapNode( this.envNode );
  13220. }
  13221. }
  13222. /**
  13223. * A specific version of {@link IrradianceNode} that is only relevant
  13224. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  13225. * requires a special scaling factor for the light map.
  13226. *
  13227. * @augments LightingNode
  13228. */
  13229. class BasicLightMapNode extends LightingNode {
  13230. static get type() {
  13231. return 'BasicLightMapNode';
  13232. }
  13233. /**
  13234. * Constructs a new basic light map node.
  13235. *
  13236. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  13237. */
  13238. constructor( lightMapNode = null ) {
  13239. super();
  13240. /**
  13241. * The light map node.
  13242. *
  13243. * @type {?Node<vec3>}
  13244. */
  13245. this.lightMapNode = lightMapNode;
  13246. }
  13247. setup( builder ) {
  13248. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  13249. const RECIPROCAL_PI = float( 1 / Math.PI );
  13250. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  13251. }
  13252. }
  13253. /**
  13254. * Abstract class for implementing lighting models. The module defines
  13255. * multiple methods that concrete lighting models can implement. These
  13256. * methods are executed at different points during the light evaluation
  13257. * process.
  13258. */
  13259. class LightingModel {
  13260. /**
  13261. * This method is intended for setting up lighting model and context data
  13262. * which are later used in the evaluation process.
  13263. *
  13264. * @abstract
  13265. * @param {NodeBuilder} builder - The current node builder.
  13266. */
  13267. start( builder ) {
  13268. // lights ( direct )
  13269. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  13270. // indirect
  13271. this.indirect( builder );
  13272. }
  13273. /**
  13274. * This method is intended for executing final tasks like final updates
  13275. * to the outgoing light.
  13276. *
  13277. * @abstract
  13278. * @param {NodeBuilder} builder - The current node builder.
  13279. */
  13280. finish( /*builder*/ ) { }
  13281. /**
  13282. * This method is intended for implementing the direct light term and
  13283. * executed during the build process of directional, point and spot light nodes.
  13284. *
  13285. * @abstract
  13286. * @param {Object} lightData - The light data.
  13287. * @param {NodeBuilder} builder - The current node builder.
  13288. */
  13289. direct( /*lightData, builder*/ ) { }
  13290. /**
  13291. * This method is intended for implementing the direct light term for
  13292. * rect area light nodes.
  13293. *
  13294. * @abstract
  13295. * @param {Object} lightData - The light data.
  13296. * @param {NodeBuilder} builder - The current node builder.
  13297. */
  13298. directRectArea( /*lightData, builder*/ ) {}
  13299. /**
  13300. * This method is intended for implementing the indirect light term.
  13301. *
  13302. * @abstract
  13303. * @param {NodeBuilder} builder - The current node builder.
  13304. */
  13305. indirect( /*builder*/ ) { }
  13306. /**
  13307. * This method is intended for implementing the ambient occlusion term.
  13308. * Unlike other methods, this method must be called manually by the lighting
  13309. * model in its indirect term.
  13310. *
  13311. * @abstract
  13312. * @param {NodeBuilder} builder - The current node builder.
  13313. */
  13314. ambientOcclusion( /*input, stack, builder*/ ) { }
  13315. }
  13316. /**
  13317. * Represents the lighting model for unlit materials. The only light contribution
  13318. * is baked indirect lighting modulated with ambient occlusion and the material's
  13319. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  13320. *
  13321. * @augments LightingModel
  13322. */
  13323. class BasicLightingModel extends LightingModel {
  13324. /**
  13325. * Constructs a new basic lighting model.
  13326. */
  13327. constructor() {
  13328. super();
  13329. }
  13330. /**
  13331. * Implements the baked indirect lighting with its modulation.
  13332. *
  13333. * @param {NodeBuilder} builder - The current node builder.
  13334. */
  13335. indirect( { context } ) {
  13336. const ambientOcclusion = context.ambientOcclusion;
  13337. const reflectedLight = context.reflectedLight;
  13338. const irradianceLightMap = context.irradianceLightMap;
  13339. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  13340. // accumulation (baked indirect lighting only)
  13341. if ( irradianceLightMap ) {
  13342. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  13343. } else {
  13344. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  13345. }
  13346. // modulation
  13347. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13348. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  13349. }
  13350. /**
  13351. * Implements the environment mapping.
  13352. *
  13353. * @param {NodeBuilder} builder - The current node builder.
  13354. */
  13355. finish( builder ) {
  13356. const { material, context } = builder;
  13357. const outgoingLight = context.outgoingLight;
  13358. const envNode = builder.context.environment;
  13359. if ( envNode ) {
  13360. switch ( material.combine ) {
  13361. case MultiplyOperation:
  13362. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  13363. break;
  13364. case MixOperation:
  13365. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  13366. break;
  13367. case AddOperation:
  13368. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  13369. break;
  13370. default:
  13371. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  13372. break;
  13373. }
  13374. }
  13375. }
  13376. }
  13377. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  13378. /**
  13379. * Node material version of {@link MeshBasicMaterial}.
  13380. *
  13381. * @augments NodeMaterial
  13382. */
  13383. class MeshBasicNodeMaterial extends NodeMaterial {
  13384. static get type() {
  13385. return 'MeshBasicNodeMaterial';
  13386. }
  13387. /**
  13388. * Constructs a new mesh basic node material.
  13389. *
  13390. * @param {Object} [parameters] - The configuration parameter.
  13391. */
  13392. constructor( parameters ) {
  13393. super();
  13394. /**
  13395. * This flag can be used for type testing.
  13396. *
  13397. * @type {boolean}
  13398. * @readonly
  13399. * @default true
  13400. */
  13401. this.isMeshBasicNodeMaterial = true;
  13402. /**
  13403. * Although the basic material is by definition unlit, we set
  13404. * this property to `true` since we use a lighting model to compute
  13405. * the outgoing light of the fragment shader.
  13406. *
  13407. * @type {boolean}
  13408. * @default true
  13409. */
  13410. this.lights = true;
  13411. this.setDefaultValues( _defaultValues$9 );
  13412. this.setValues( parameters );
  13413. }
  13414. /**
  13415. * Basic materials are not affected by normal and bump maps so we
  13416. * return by default {@link normalView}.
  13417. *
  13418. * @return {Node<vec3>} The normal node.
  13419. */
  13420. setupNormal() {
  13421. return normalView; // see #28839
  13422. }
  13423. /**
  13424. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13425. * to implement the default environment mapping.
  13426. *
  13427. * @param {NodeBuilder} builder - The current node builder.
  13428. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13429. */
  13430. setupEnvironment( builder ) {
  13431. const envNode = super.setupEnvironment( builder );
  13432. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13433. }
  13434. /**
  13435. * This method must be overwritten since light maps are evaluated
  13436. * with a special scaling factor for basic materials.
  13437. *
  13438. * @param {NodeBuilder} builder - The current node builder.
  13439. * @return {?BasicLightMapNode<vec3>} The light map node.
  13440. */
  13441. setupLightMap( builder ) {
  13442. let node = null;
  13443. if ( builder.material.lightMap ) {
  13444. node = new BasicLightMapNode( materialLightMap );
  13445. }
  13446. return node;
  13447. }
  13448. /**
  13449. * The material overwrites this method because `lights` is set to `true` but
  13450. * we still want to return the diffuse color as the outgoing light.
  13451. *
  13452. * @return {Node<vec3>} The outgoing light node.
  13453. */
  13454. setupOutgoingLight() {
  13455. return diffuseColor.rgb;
  13456. }
  13457. /**
  13458. * Setups the lighting model.
  13459. *
  13460. * @return {BasicLightingModel} The lighting model.
  13461. */
  13462. setupLightingModel() {
  13463. return new BasicLightingModel();
  13464. }
  13465. }
  13466. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  13467. // Original approximation by Christophe Schlick '94
  13468. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  13469. // Optimized variant (presented by Epic at SIGGRAPH '13)
  13470. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  13471. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  13472. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  13473. } ); // validated
  13474. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  13475. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  13476. } ); // validated
  13477. const G_BlinnPhong_Implicit = () => float( 0.25 );
  13478. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  13479. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  13480. } );
  13481. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13482. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13483. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13484. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13485. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  13486. const G = G_BlinnPhong_Implicit();
  13487. const D = D_BlinnPhong( { dotNH } );
  13488. return F.mul( G ).mul( D );
  13489. } );
  13490. /**
  13491. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  13492. *
  13493. * @augments BasicLightingModel
  13494. */
  13495. class PhongLightingModel extends BasicLightingModel {
  13496. /**
  13497. * Constructs a new phong lighting model.
  13498. *
  13499. * @param {boolean} [specular=true] - Whether specular is supported or not.
  13500. */
  13501. constructor( specular = true ) {
  13502. super();
  13503. /**
  13504. * Whether specular is supported or not. Set this to `false` if you are
  13505. * looking for a Lambert-like material meaning a material for non-shiny
  13506. * surfaces, without specular highlights.
  13507. *
  13508. * @type {boolean}
  13509. * @default true
  13510. */
  13511. this.specular = specular;
  13512. }
  13513. /**
  13514. * Implements the direct lighting. The specular portion is optional an can be controlled
  13515. * with the {@link PhongLightingModel#specular} flag.
  13516. *
  13517. * @param {Object} lightData - The light data.
  13518. */
  13519. direct( { lightDirection, lightColor, reflectedLight } ) {
  13520. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13521. const irradiance = dotNL.mul( lightColor );
  13522. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13523. if ( this.specular === true ) {
  13524. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  13525. }
  13526. }
  13527. /**
  13528. * Implements the indirect lighting.
  13529. *
  13530. * @param {NodeBuilder} builder - The current node builder.
  13531. */
  13532. indirect( builder ) {
  13533. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  13534. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13535. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13536. }
  13537. }
  13538. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  13539. /**
  13540. * Node material version of {@link MeshLambertMaterial}.
  13541. *
  13542. * @augments NodeMaterial
  13543. */
  13544. class MeshLambertNodeMaterial extends NodeMaterial {
  13545. static get type() {
  13546. return 'MeshLambertNodeMaterial';
  13547. }
  13548. /**
  13549. * Constructs a new mesh lambert node material.
  13550. *
  13551. * @param {Object} [parameters] - The configuration parameter.
  13552. */
  13553. constructor( parameters ) {
  13554. super();
  13555. /**
  13556. * This flag can be used for type testing.
  13557. *
  13558. * @type {boolean}
  13559. * @readonly
  13560. * @default true
  13561. */
  13562. this.isMeshLambertNodeMaterial = true;
  13563. /**
  13564. * Set to `true` because lambert materials react on lights.
  13565. *
  13566. * @type {boolean}
  13567. * @default true
  13568. */
  13569. this.lights = true;
  13570. this.setDefaultValues( _defaultValues$8 );
  13571. this.setValues( parameters );
  13572. }
  13573. /**
  13574. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13575. * to implement the default environment mapping.
  13576. *
  13577. * @param {NodeBuilder} builder - The current node builder.
  13578. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13579. */
  13580. setupEnvironment( builder ) {
  13581. const envNode = super.setupEnvironment( builder );
  13582. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13583. }
  13584. /**
  13585. * Setups the lighting model.
  13586. *
  13587. * @return {PhongLightingModel} The lighting model.
  13588. */
  13589. setupLightingModel( /*builder*/ ) {
  13590. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13591. }
  13592. }
  13593. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13594. /**
  13595. * Node material version of {@link MeshPhongMaterial}.
  13596. *
  13597. * @augments NodeMaterial
  13598. */
  13599. class MeshPhongNodeMaterial extends NodeMaterial {
  13600. static get type() {
  13601. return 'MeshPhongNodeMaterial';
  13602. }
  13603. /**
  13604. * Constructs a new mesh lambert node material.
  13605. *
  13606. * @param {Object} [parameters] - The configuration parameter.
  13607. */
  13608. constructor( parameters ) {
  13609. super();
  13610. /**
  13611. * This flag can be used for type testing.
  13612. *
  13613. * @type {boolean}
  13614. * @readonly
  13615. * @default true
  13616. */
  13617. this.isMeshPhongNodeMaterial = true;
  13618. /**
  13619. * Set to `true` because phong materials react on lights.
  13620. *
  13621. * @type {boolean}
  13622. * @default true
  13623. */
  13624. this.lights = true;
  13625. /**
  13626. * The shininess of phong materials is by default inferred from the `shininess`
  13627. * property. This node property allows to overwrite the default
  13628. * and define the shininess with a node instead.
  13629. *
  13630. * If you don't want to overwrite the shininess but modify the existing
  13631. * value instead, use {@link materialShininess}.
  13632. *
  13633. * @type {?Node<float>}
  13634. * @default null
  13635. */
  13636. this.shininessNode = null;
  13637. /**
  13638. * The specular color of phong materials is by default inferred from the
  13639. * `specular` property. This node property allows to overwrite the default
  13640. * and define the specular color with a node instead.
  13641. *
  13642. * If you don't want to overwrite the specular color but modify the existing
  13643. * value instead, use {@link materialSpecular}.
  13644. *
  13645. * @type {?Node<vec3>}
  13646. * @default null
  13647. */
  13648. this.specularNode = null;
  13649. this.setDefaultValues( _defaultValues$7 );
  13650. this.setValues( parameters );
  13651. }
  13652. /**
  13653. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13654. * to implement the default environment mapping.
  13655. *
  13656. * @param {NodeBuilder} builder - The current node builder.
  13657. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  13658. */
  13659. setupEnvironment( builder ) {
  13660. const envNode = super.setupEnvironment( builder );
  13661. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13662. }
  13663. /**
  13664. * Setups the lighting model.
  13665. *
  13666. * @return {PhongLightingModel} The lighting model.
  13667. */
  13668. setupLightingModel( /*builder*/ ) {
  13669. return new PhongLightingModel();
  13670. }
  13671. /**
  13672. * Setups the phong specific node variables.
  13673. *
  13674. * @param {NodeBuilder} builder - The current node builder.
  13675. */
  13676. setupVariants( /*builder*/ ) {
  13677. // SHININESS
  13678. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13679. shininess.assign( shininessNode );
  13680. // SPECULAR COLOR
  13681. const specularNode = this.specularNode || materialSpecular;
  13682. specularColor.assign( specularNode );
  13683. }
  13684. copy( source ) {
  13685. this.shininessNode = source.shininessNode;
  13686. this.specularNode = source.specularNode;
  13687. return super.copy( source );
  13688. }
  13689. }
  13690. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13691. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13692. return float( 0 );
  13693. }
  13694. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13695. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13696. return geometryRoughness;
  13697. } );
  13698. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13699. const { roughness } = inputs;
  13700. const geometryRoughness = getGeometryRoughness();
  13701. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13702. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13703. roughnessFactor = roughnessFactor.min( 1.0 );
  13704. return roughnessFactor;
  13705. } );
  13706. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13707. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13708. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13709. const a2 = alpha.pow2();
  13710. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13711. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13712. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13713. } ).setLayout( {
  13714. name: 'V_GGX_SmithCorrelated',
  13715. type: 'float',
  13716. inputs: [
  13717. { name: 'alpha', type: 'float' },
  13718. { name: 'dotNL', type: 'float' },
  13719. { name: 'dotNV', type: 'float' }
  13720. ]
  13721. } ); // validated
  13722. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13723. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13724. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13725. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13726. const v = div( 0.5, gv.add( gl ) );
  13727. return v.saturate();
  13728. } ).setLayout( {
  13729. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13730. type: 'float',
  13731. inputs: [
  13732. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13733. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13734. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13735. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13736. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13737. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13738. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13739. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13740. ]
  13741. } );
  13742. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13743. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13744. // alpha is "roughness squared" in Disney’s reparameterization
  13745. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13746. const a2 = alpha.pow2();
  13747. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13748. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13749. } ).setLayout( {
  13750. name: 'D_GGX',
  13751. type: 'float',
  13752. inputs: [
  13753. { name: 'alpha', type: 'float' },
  13754. { name: 'dotNH', type: 'float' }
  13755. ]
  13756. } ); // validated
  13757. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13758. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13759. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13760. const a2 = alphaT.mul( alphaB );
  13761. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13762. const v2 = v.dot( v );
  13763. const w2 = a2.div( v2 );
  13764. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13765. } ).setLayout( {
  13766. name: 'D_GGX_Anisotropic',
  13767. type: 'float',
  13768. inputs: [
  13769. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13770. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13771. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13772. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13773. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13774. ]
  13775. } );
  13776. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13777. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13778. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13779. const normalView = inputs.normalView || transformedNormalView;
  13780. const alpha = roughness.pow2(); // UE4's roughness
  13781. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13782. const dotNL = normalView.dot( lightDirection ).clamp();
  13783. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13784. const dotNH = normalView.dot( halfDir ).clamp();
  13785. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13786. let F = F_Schlick( { f0, f90, dotVH } );
  13787. let V, D;
  13788. if ( defined( USE_IRIDESCENCE ) ) {
  13789. F = iridescence.mix( F, f );
  13790. }
  13791. if ( defined( USE_ANISOTROPY ) ) {
  13792. const dotTL = anisotropyT.dot( lightDirection );
  13793. const dotTV = anisotropyT.dot( positionViewDirection );
  13794. const dotTH = anisotropyT.dot( halfDir );
  13795. const dotBL = anisotropyB.dot( lightDirection );
  13796. const dotBV = anisotropyB.dot( positionViewDirection );
  13797. const dotBH = anisotropyB.dot( halfDir );
  13798. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13799. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13800. } else {
  13801. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13802. D = D_GGX( { alpha, dotNH } );
  13803. }
  13804. return F.mul( V ).mul( D );
  13805. } ); // validated
  13806. // Analytical approximation of the DFG LUT, one half of the
  13807. // split-sum approximation used in indirect specular lighting.
  13808. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13809. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13810. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13811. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  13812. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  13813. const r = roughness.mul( c0 ).add( c1 );
  13814. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  13815. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  13816. return fab;
  13817. } ).setLayout( {
  13818. name: 'DFGApprox',
  13819. type: 'vec2',
  13820. inputs: [
  13821. { name: 'roughness', type: 'float' },
  13822. { name: 'dotNV', type: 'vec3' }
  13823. ]
  13824. } );
  13825. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13826. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13827. const fab = DFGApprox( { dotNV, roughness } );
  13828. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13829. } );
  13830. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13831. const x = dotVH.oneMinus().saturate();
  13832. const x2 = x.mul( x );
  13833. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13834. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13835. } ).setLayout( {
  13836. name: 'Schlick_to_F0',
  13837. type: 'vec3',
  13838. inputs: [
  13839. { name: 'f', type: 'vec3' },
  13840. { name: 'f90', type: 'float' },
  13841. { name: 'dotVH', type: 'float' }
  13842. ]
  13843. } );
  13844. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13845. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13846. const alpha = roughness.pow2();
  13847. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13848. const invAlpha = float( 1.0 ).div( alpha );
  13849. const cos2h = dotNH.pow2();
  13850. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13851. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13852. } ).setLayout( {
  13853. name: 'D_Charlie',
  13854. type: 'float',
  13855. inputs: [
  13856. { name: 'roughness', type: 'float' },
  13857. { name: 'dotNH', type: 'float' }
  13858. ]
  13859. } );
  13860. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13861. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13862. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13863. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13864. } ).setLayout( {
  13865. name: 'V_Neubelt',
  13866. type: 'float',
  13867. inputs: [
  13868. { name: 'dotNV', type: 'float' },
  13869. { name: 'dotNL', type: 'float' }
  13870. ]
  13871. } );
  13872. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13873. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13874. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13875. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13876. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13877. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13878. const V = V_Neubelt( { dotNV, dotNL } );
  13879. return sheen.mul( D ).mul( V );
  13880. } );
  13881. // Rect Area Light
  13882. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13883. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13884. // code: https://github.com/selfshadow/ltc_code/
  13885. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13886. const LUT_SIZE = 64.0;
  13887. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13888. const LUT_BIAS = 0.5 / LUT_SIZE;
  13889. const dotNV = N.dot( V ).saturate();
  13890. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13891. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13892. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13893. return uv;
  13894. } ).setLayout( {
  13895. name: 'LTC_Uv',
  13896. type: 'vec2',
  13897. inputs: [
  13898. { name: 'N', type: 'vec3' },
  13899. { name: 'V', type: 'vec3' },
  13900. { name: 'roughness', type: 'float' }
  13901. ]
  13902. } );
  13903. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13904. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13905. // An approximation of the form factor of a horizon-clipped rectangle.
  13906. const l = f.length();
  13907. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13908. } ).setLayout( {
  13909. name: 'LTC_ClippedSphereFormFactor',
  13910. type: 'float',
  13911. inputs: [
  13912. { name: 'f', type: 'vec3' }
  13913. ]
  13914. } );
  13915. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13916. const x = v1.dot( v2 );
  13917. const y = x.abs().toVar();
  13918. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13919. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13920. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13921. const v = a.div( b );
  13922. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13923. return v1.cross( v2 ).mul( theta_sintheta );
  13924. } ).setLayout( {
  13925. name: 'LTC_EdgeVectorFormFactor',
  13926. type: 'vec3',
  13927. inputs: [
  13928. { name: 'v1', type: 'vec3' },
  13929. { name: 'v2', type: 'vec3' }
  13930. ]
  13931. } );
  13932. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13933. // bail if point is on back side of plane of light
  13934. // assumes ccw winding order of light vertices
  13935. const v1 = p1.sub( p0 ).toVar();
  13936. const v2 = p3.sub( p0 ).toVar();
  13937. const lightNormal = v1.cross( v2 );
  13938. const result = vec3().toVar();
  13939. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13940. // construct orthonormal basis around N
  13941. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13942. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13943. // compute transform
  13944. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13945. // transform rect
  13946. // & project rect onto sphere
  13947. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13948. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13949. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13950. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13951. // calculate vector form factor
  13952. const vectorFormFactor = vec3( 0 ).toVar();
  13953. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13954. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13955. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13956. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13957. // adjust for horizon clipping
  13958. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13959. } );
  13960. return result;
  13961. } ).setLayout( {
  13962. name: 'LTC_Evaluate',
  13963. type: 'vec3',
  13964. inputs: [
  13965. { name: 'N', type: 'vec3' },
  13966. { name: 'V', type: 'vec3' },
  13967. { name: 'P', type: 'vec3' },
  13968. { name: 'mInv', type: 'mat3' },
  13969. { name: 'p0', type: 'vec3' },
  13970. { name: 'p1', type: 'vec3' },
  13971. { name: 'p2', type: 'vec3' },
  13972. { name: 'p3', type: 'vec3' }
  13973. ]
  13974. } );
  13975. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  13976. // bail if point is on back side of plane of light
  13977. // assumes ccw winding order of light vertices
  13978. const v1 = p1.sub( p0 ).toVar();
  13979. const v2 = p3.sub( p0 ).toVar();
  13980. const lightNormal = v1.cross( v2 );
  13981. const result = vec3().toVar();
  13982. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13983. // transform rect
  13984. // & project rect onto sphere
  13985. const coords0 = p0.sub( P ).normalize().toVar();
  13986. const coords1 = p1.sub( P ).normalize().toVar();
  13987. const coords2 = p2.sub( P ).normalize().toVar();
  13988. const coords3 = p3.sub( P ).normalize().toVar();
  13989. // calculate vector form factor
  13990. const vectorFormFactor = vec3( 0 ).toVar();
  13991. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13992. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13993. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13994. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13995. // adjust for horizon clipping
  13996. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  13997. } );
  13998. return result;
  13999. } ).setLayout( {
  14000. name: 'LTC_Evaluate',
  14001. type: 'vec3',
  14002. inputs: [
  14003. { name: 'P', type: 'vec3' },
  14004. { name: 'p0', type: 'vec3' },
  14005. { name: 'p1', type: 'vec3' },
  14006. { name: 'p2', type: 'vec3' },
  14007. { name: 'p3', type: 'vec3' }
  14008. ]
  14009. } );
  14010. // Mipped Bicubic Texture Filtering by N8
  14011. // https://www.shadertoy.com/view/Dl2SDW
  14012. const bC = 1.0 / 6.0;
  14013. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  14014. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  14015. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  14016. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  14017. const g0 = ( a ) => w0( a ).add( w1( a ) );
  14018. const g1 = ( a ) => w2( a ).add( w3( a ) );
  14019. // h0 and h1 are the two offset functions
  14020. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  14021. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  14022. const bicubic = ( textureNode, texelSize, lod ) => {
  14023. const uv = textureNode.uvNode;
  14024. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  14025. const iuv = floor( uvScaled );
  14026. const fuv = fract( uvScaled );
  14027. const g0x = g0( fuv.x );
  14028. const g1x = g1( fuv.x );
  14029. const h0x = h0( fuv.x );
  14030. const h1x = h1( fuv.x );
  14031. const h0y = h0( fuv.y );
  14032. const h1y = h1( fuv.y );
  14033. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  14034. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  14035. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  14036. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  14037. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  14038. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  14039. return a.add( b );
  14040. };
  14041. /**
  14042. * Applies mipped bicubic texture filtering to the given texture node.
  14043. *
  14044. * @tsl
  14045. * @function
  14046. * @param {TextureNode} textureNode - The texture node that should be filtered.
  14047. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  14048. * @return {Node} The filtered texture sample.
  14049. */
  14050. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  14051. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  14052. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  14053. const fLodSizeInv = div( 1.0, fLodSize );
  14054. const cLodSizeInv = div( 1.0, cLodSize );
  14055. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  14056. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  14057. return fract( lodNode ).mix( fSample, cSample );
  14058. } );
  14059. //
  14060. // Transmission
  14061. //
  14062. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  14063. // Direction of refracted light.
  14064. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  14065. // Compute rotation-independent scaling of the model matrix.
  14066. const modelScale = vec3(
  14067. length( modelMatrix[ 0 ].xyz ),
  14068. length( modelMatrix[ 1 ].xyz ),
  14069. length( modelMatrix[ 2 ].xyz )
  14070. );
  14071. // The thickness is specified in local space.
  14072. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  14073. } ).setLayout( {
  14074. name: 'getVolumeTransmissionRay',
  14075. type: 'vec3',
  14076. inputs: [
  14077. { name: 'n', type: 'vec3' },
  14078. { name: 'v', type: 'vec3' },
  14079. { name: 'thickness', type: 'float' },
  14080. { name: 'ior', type: 'float' },
  14081. { name: 'modelMatrix', type: 'mat4' }
  14082. ]
  14083. } );
  14084. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  14085. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  14086. // an IOR of 1.5 results in the default amount of microfacet refraction.
  14087. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  14088. } ).setLayout( {
  14089. name: 'applyIorToRoughness',
  14090. type: 'float',
  14091. inputs: [
  14092. { name: 'roughness', type: 'float' },
  14093. { name: 'ior', type: 'float' }
  14094. ]
  14095. } );
  14096. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  14097. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  14098. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  14099. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  14100. const transmissionSample = vTexture.sample( fragCoord );
  14101. //const transmissionSample = viewportMipTexture( fragCoord );
  14102. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  14103. return textureBicubic( transmissionSample, lod );
  14104. } );
  14105. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  14106. If( attenuationDistance.notEqual( 0 ), () => {
  14107. // Compute light attenuation using Beer's law.
  14108. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  14109. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  14110. return transmittance;
  14111. } );
  14112. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  14113. return vec3( 1.0 );
  14114. } ).setLayout( {
  14115. name: 'volumeAttenuation',
  14116. type: 'vec3',
  14117. inputs: [
  14118. { name: 'transmissionDistance', type: 'float' },
  14119. { name: 'attenuationColor', type: 'vec3' },
  14120. { name: 'attenuationDistance', type: 'float' }
  14121. ]
  14122. } );
  14123. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  14124. let transmittedLight, transmittance;
  14125. if ( dispersion ) {
  14126. transmittedLight = vec4().toVar();
  14127. transmittance = vec3().toVar();
  14128. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  14129. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  14130. Loop( { start: 0, end: 3 }, ( { i } ) => {
  14131. const ior = iors.element( i );
  14132. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  14133. const refractedRayExit = position.add( transmissionRay );
  14134. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  14135. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  14136. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  14137. refractionCoords.addAssign( 1.0 );
  14138. refractionCoords.divAssign( 2.0 );
  14139. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  14140. // Sample framebuffer to get pixel the refracted ray hits.
  14141. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  14142. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  14143. transmittedLight.a.addAssign( transmissionSample.a );
  14144. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  14145. } );
  14146. transmittedLight.a.divAssign( 3.0 );
  14147. } else {
  14148. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  14149. const refractedRayExit = position.add( transmissionRay );
  14150. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  14151. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  14152. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  14153. refractionCoords.addAssign( 1.0 );
  14154. refractionCoords.divAssign( 2.0 );
  14155. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  14156. // Sample framebuffer to get pixel the refracted ray hits.
  14157. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  14158. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  14159. }
  14160. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  14161. const dotNV = n.dot( v ).clamp();
  14162. // Get the specular component.
  14163. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  14164. dotNV,
  14165. specularColor,
  14166. specularF90,
  14167. roughness
  14168. } ) );
  14169. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  14170. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  14171. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  14172. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  14173. } );
  14174. //
  14175. // Iridescence
  14176. //
  14177. // XYZ to linear-sRGB color space
  14178. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  14179. 3.2404542, -0.969266, 0.0556434,
  14180. -1.5371385, 1.8760108, -0.2040259,
  14181. -0.4985314, 0.0415560, 1.0572252
  14182. );
  14183. // Assume air interface for top
  14184. // Note: We don't handle the case fresnel0 == 1
  14185. const Fresnel0ToIor = ( fresnel0 ) => {
  14186. const sqrtF0 = fresnel0.sqrt();
  14187. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  14188. };
  14189. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  14190. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  14191. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  14192. };
  14193. // Fresnel equations for dielectric/dielectric interfaces.
  14194. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  14195. // Evaluation XYZ sensitivity curves in Fourier space
  14196. const evalSensitivity = ( OPD, shift ) => {
  14197. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  14198. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  14199. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  14200. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  14201. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( -45282e5 ).exp() );
  14202. 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() );
  14203. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  14204. const rgb = XYZ_TO_REC709.mul( xyz );
  14205. return rgb;
  14206. };
  14207. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  14208. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  14209. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  14210. // Evaluate the cosTheta on the base layer (Snell law)
  14211. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  14212. // Handle TIR:
  14213. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  14214. If( cosTheta2Sq.lessThan( 0 ), () => {
  14215. return vec3( 1.0 );
  14216. } );
  14217. const cosTheta2 = cosTheta2Sq.sqrt();
  14218. // First interface
  14219. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  14220. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  14221. //const R21 = R12;
  14222. const T121 = R12.oneMinus();
  14223. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  14224. const phi21 = float( Math.PI ).sub( phi12 );
  14225. // Second interface
  14226. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  14227. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  14228. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  14229. const phi23 = vec3(
  14230. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  14231. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  14232. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  14233. );
  14234. // Phase shift
  14235. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  14236. const phi = vec3( phi21 ).add( phi23 );
  14237. // Compound terms
  14238. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  14239. const r123 = R123.sqrt();
  14240. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  14241. // Reflectance term for m = 0 (DC term amplitude)
  14242. const C0 = R12.add( Rs );
  14243. const I = C0.toVar();
  14244. // Reflectance term for m > 0 (pairs of diracs)
  14245. const Cm = Rs.sub( T121 ).toVar();
  14246. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  14247. Cm.mulAssign( r123 );
  14248. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  14249. I.addAssign( Cm.mul( Sm ) );
  14250. } );
  14251. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  14252. return I.max( vec3( 0.0 ) );
  14253. } ).setLayout( {
  14254. name: 'evalIridescence',
  14255. type: 'vec3',
  14256. inputs: [
  14257. { name: 'outsideIOR', type: 'float' },
  14258. { name: 'eta2', type: 'float' },
  14259. { name: 'cosTheta1', type: 'float' },
  14260. { name: 'thinFilmThickness', type: 'float' },
  14261. { name: 'baseF0', type: 'vec3' }
  14262. ]
  14263. } );
  14264. //
  14265. // Sheen
  14266. //
  14267. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  14268. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  14269. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  14270. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  14271. const dotNV = normal.dot( viewDir ).saturate();
  14272. const r2 = roughness.pow2();
  14273. const a = select(
  14274. roughness.lessThan( 0.25 ),
  14275. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  14276. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  14277. );
  14278. const b = select(
  14279. roughness.lessThan( 0.25 ),
  14280. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  14281. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  14282. );
  14283. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  14284. return DG.mul( 1.0 / Math.PI ).saturate();
  14285. } );
  14286. const clearcoatF0 = vec3( 0.04 );
  14287. const clearcoatF90 = float( 1 );
  14288. /**
  14289. * Represents the lighting model for a PBR material.
  14290. *
  14291. * @augments LightingModel
  14292. */
  14293. class PhysicalLightingModel extends LightingModel {
  14294. /**
  14295. * Constructs a new physical lighting model.
  14296. *
  14297. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  14298. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  14299. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  14300. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  14301. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  14302. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  14303. */
  14304. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  14305. super();
  14306. /**
  14307. * Whether clearcoat is supported or not.
  14308. *
  14309. * @type {boolean}
  14310. * @default false
  14311. */
  14312. this.clearcoat = clearcoat;
  14313. /**
  14314. * Whether sheen is supported or not.
  14315. *
  14316. * @type {boolean}
  14317. * @default false
  14318. */
  14319. this.sheen = sheen;
  14320. /**
  14321. * Whether iridescence is supported or not.
  14322. *
  14323. * @type {boolean}
  14324. * @default false
  14325. */
  14326. this.iridescence = iridescence;
  14327. /**
  14328. * Whether anisotropy is supported or not.
  14329. *
  14330. * @type {boolean}
  14331. * @default false
  14332. */
  14333. this.anisotropy = anisotropy;
  14334. /**
  14335. * Whether transmission is supported or not.
  14336. *
  14337. * @type {boolean}
  14338. * @default false
  14339. */
  14340. this.transmission = transmission;
  14341. /**
  14342. * Whether dispersion is supported or not.
  14343. *
  14344. * @type {boolean}
  14345. * @default false
  14346. */
  14347. this.dispersion = dispersion;
  14348. /**
  14349. * The clear coat radiance.
  14350. *
  14351. * @type {?Node}
  14352. * @default null
  14353. */
  14354. this.clearcoatRadiance = null;
  14355. /**
  14356. * The clear coat specular direct.
  14357. *
  14358. * @type {?Node}
  14359. * @default null
  14360. */
  14361. this.clearcoatSpecularDirect = null;
  14362. /**
  14363. * The clear coat specular indirect.
  14364. *
  14365. * @type {?Node}
  14366. * @default null
  14367. */
  14368. this.clearcoatSpecularIndirect = null;
  14369. /**
  14370. * The sheen specular direct.
  14371. *
  14372. * @type {?Node}
  14373. * @default null
  14374. */
  14375. this.sheenSpecularDirect = null;
  14376. /**
  14377. * The sheen specular indirect.
  14378. *
  14379. * @type {?Node}
  14380. * @default null
  14381. */
  14382. this.sheenSpecularIndirect = null;
  14383. /**
  14384. * The iridescence Fresnel.
  14385. *
  14386. * @type {?Node}
  14387. * @default null
  14388. */
  14389. this.iridescenceFresnel = null;
  14390. /**
  14391. * The iridescence F0.
  14392. *
  14393. * @type {?Node}
  14394. * @default null
  14395. */
  14396. this.iridescenceF0 = null;
  14397. }
  14398. /**
  14399. * Depending on what features are requested, the method prepares certain node variables
  14400. * which are later used for lighting computations.
  14401. *
  14402. * @param {NodeBuilder} builder - The current node builder.
  14403. */
  14404. start( builder ) {
  14405. if ( this.clearcoat === true ) {
  14406. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  14407. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  14408. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  14409. }
  14410. if ( this.sheen === true ) {
  14411. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  14412. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  14413. }
  14414. if ( this.iridescence === true ) {
  14415. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  14416. this.iridescenceFresnel = evalIridescence( {
  14417. outsideIOR: float( 1.0 ),
  14418. eta2: iridescenceIOR,
  14419. cosTheta1: dotNVi,
  14420. thinFilmThickness: iridescenceThickness,
  14421. baseF0: specularColor
  14422. } );
  14423. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  14424. }
  14425. if ( this.transmission === true ) {
  14426. const position = positionWorld;
  14427. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  14428. const n = transformedNormalWorld;
  14429. const context = builder.context;
  14430. context.backdrop = getIBLVolumeRefraction(
  14431. n,
  14432. v,
  14433. roughness,
  14434. diffuseColor,
  14435. specularColor,
  14436. specularF90, // specularF90
  14437. position, // positionWorld
  14438. modelWorldMatrix, // modelMatrix
  14439. cameraViewMatrix, // viewMatrix
  14440. cameraProjectionMatrix, // projMatrix
  14441. ior,
  14442. thickness,
  14443. attenuationColor,
  14444. attenuationDistance,
  14445. this.dispersion ? dispersion : null
  14446. );
  14447. context.backdropAlpha = transmission;
  14448. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  14449. }
  14450. super.start( builder );
  14451. }
  14452. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  14453. // Approximates multi-scattering in order to preserve energy.
  14454. // http://www.jcgt.org/published/0008/01/03/
  14455. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  14456. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14457. const fab = DFGApprox( { roughness, dotNV } );
  14458. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  14459. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  14460. const Ess = fab.x.add( fab.y );
  14461. const Ems = Ess.oneMinus();
  14462. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  14463. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  14464. singleScatter.addAssign( FssEss );
  14465. multiScatter.addAssign( Fms.mul( Ems ) );
  14466. }
  14467. /**
  14468. * Implements the direct light.
  14469. *
  14470. * @param {Object} lightData - The light data.
  14471. * @param {NodeBuilder} builder - The current node builder.
  14472. */
  14473. direct( { lightDirection, lightColor, reflectedLight } ) {
  14474. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14475. const irradiance = dotNL.mul( lightColor );
  14476. if ( this.sheen === true ) {
  14477. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  14478. }
  14479. if ( this.clearcoat === true ) {
  14480. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  14481. const ccIrradiance = dotNLcc.mul( lightColor );
  14482. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  14483. }
  14484. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14485. 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 } ) ) );
  14486. }
  14487. /**
  14488. * This method is intended for implementing the direct light term for
  14489. * rect area light nodes.
  14490. *
  14491. * @param {Object} input - The input data.
  14492. * @param {NodeBuilder} builder - The current node builder.
  14493. */
  14494. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  14495. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  14496. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  14497. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  14498. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  14499. const N = transformedNormalView;
  14500. const V = positionViewDirection;
  14501. const P = positionView.toVar();
  14502. const uv = LTC_Uv( { N, V, roughness } );
  14503. const t1 = ltc_1.sample( uv ).toVar();
  14504. const t2 = ltc_2.sample( uv ).toVar();
  14505. const mInv = mat3(
  14506. vec3( t1.x, 0, t1.y ),
  14507. vec3( 0, 1, 0 ),
  14508. vec3( t1.z, 0, t1.w )
  14509. ).toVar();
  14510. // LTC Fresnel Approximation by Stephen Hill
  14511. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  14512. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  14513. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  14514. 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 } ) ) );
  14515. }
  14516. /**
  14517. * Implements the indirect lighting.
  14518. *
  14519. * @param {NodeBuilder} builder - The current node builder.
  14520. */
  14521. indirect( builder ) {
  14522. this.indirectDiffuse( builder );
  14523. this.indirectSpecular( builder );
  14524. this.ambientOcclusion( builder );
  14525. }
  14526. /**
  14527. * Implements the indirect diffuse term.
  14528. *
  14529. * @param {NodeBuilder} builder - The current node builder.
  14530. */
  14531. indirectDiffuse( builder ) {
  14532. const { irradiance, reflectedLight } = builder.context;
  14533. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14534. }
  14535. /**
  14536. * Implements the indirect specular term.
  14537. *
  14538. * @param {NodeBuilder} builder - The current node builder.
  14539. */
  14540. indirectSpecular( builder ) {
  14541. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  14542. if ( this.sheen === true ) {
  14543. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  14544. sheen,
  14545. IBLSheenBRDF( {
  14546. normal: transformedNormalView,
  14547. viewDir: positionViewDirection,
  14548. roughness: sheenRoughness
  14549. } )
  14550. ) );
  14551. }
  14552. if ( this.clearcoat === true ) {
  14553. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14554. const clearcoatEnv = EnvironmentBRDF( {
  14555. dotNV: dotNVcc,
  14556. specularColor: clearcoatF0,
  14557. specularF90: clearcoatF90,
  14558. roughness: clearcoatRoughness
  14559. } );
  14560. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  14561. }
  14562. // Both indirect specular and indirect diffuse light accumulate here
  14563. const singleScattering = vec3().toVar( 'singleScattering' );
  14564. const multiScattering = vec3().toVar( 'multiScattering' );
  14565. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  14566. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  14567. const totalScattering = singleScattering.add( multiScattering );
  14568. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  14569. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  14570. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  14571. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  14572. }
  14573. /**
  14574. * Implements the ambient occlusion term.
  14575. *
  14576. * @param {NodeBuilder} builder - The current node builder.
  14577. */
  14578. ambientOcclusion( builder ) {
  14579. const { ambientOcclusion, reflectedLight } = builder.context;
  14580. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14581. const aoNV = dotNV.add( ambientOcclusion );
  14582. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  14583. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  14584. if ( this.clearcoat === true ) {
  14585. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  14586. }
  14587. if ( this.sheen === true ) {
  14588. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  14589. }
  14590. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14591. reflectedLight.indirectSpecular.mulAssign( aoNode );
  14592. }
  14593. /**
  14594. * Used for final lighting accumulations depending on the requested features.
  14595. *
  14596. * @param {NodeBuilder} builder - The current node builder.
  14597. */
  14598. finish( { context } ) {
  14599. const { outgoingLight } = context;
  14600. if ( this.clearcoat === true ) {
  14601. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14602. const Fcc = F_Schlick( {
  14603. dotVH: dotNVcc,
  14604. f0: clearcoatF0,
  14605. f90: clearcoatF90
  14606. } );
  14607. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14608. outgoingLight.assign( clearcoatLight );
  14609. }
  14610. if ( this.sheen === true ) {
  14611. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14612. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14613. outgoingLight.assign( sheenLight );
  14614. }
  14615. }
  14616. }
  14617. // These defines must match with PMREMGenerator
  14618. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14619. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  14620. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14621. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  14622. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14623. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14624. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14625. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14626. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14627. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14628. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14629. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14630. // These shader functions convert between the UV coordinates of a single face of
  14631. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14632. // sampling a textureCube (not generally normalized ).
  14633. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14634. const absDirection = vec3( abs( direction ) ).toVar();
  14635. const face = float( -1 ).toVar();
  14636. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14637. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14638. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14639. } ).Else( () => {
  14640. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14641. } );
  14642. } ).Else( () => {
  14643. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14644. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14645. } ).Else( () => {
  14646. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14647. } );
  14648. } );
  14649. return face;
  14650. } ).setLayout( {
  14651. name: 'getFace',
  14652. type: 'float',
  14653. inputs: [
  14654. { name: 'direction', type: 'vec3' }
  14655. ]
  14656. } );
  14657. // RH coordinate system; PMREM face-indexing convention
  14658. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14659. const uv = vec2().toVar();
  14660. If( face.equal( 0.0 ), () => {
  14661. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14662. } ).ElseIf( face.equal( 1.0 ), () => {
  14663. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14664. } ).ElseIf( face.equal( 2.0 ), () => {
  14665. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14666. } ).ElseIf( face.equal( 3.0 ), () => {
  14667. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14668. } ).ElseIf( face.equal( 4.0 ), () => {
  14669. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14670. } ).Else( () => {
  14671. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14672. } );
  14673. return mul( 0.5, uv.add( 1.0 ) );
  14674. } ).setLayout( {
  14675. name: 'getUV',
  14676. type: 'vec2',
  14677. inputs: [
  14678. { name: 'direction', type: 'vec3' },
  14679. { name: 'face', type: 'float' }
  14680. ]
  14681. } );
  14682. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14683. const mip = float( 0.0 ).toVar();
  14684. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14685. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14686. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14687. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14688. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14689. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14690. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14691. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14692. } ).Else( () => {
  14693. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14694. } );
  14695. return mip;
  14696. } ).setLayout( {
  14697. name: 'roughnessToMip',
  14698. type: 'float',
  14699. inputs: [
  14700. { name: 'roughness', type: 'float' }
  14701. ]
  14702. } );
  14703. // RH coordinate system; PMREM face-indexing convention
  14704. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14705. const uv = uv_immutable.toVar();
  14706. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14707. const direction = vec3( uv, 1.0 ).toVar();
  14708. If( face.equal( 0.0 ), () => {
  14709. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14710. } ).ElseIf( face.equal( 1.0 ), () => {
  14711. direction.assign( direction.xzy );
  14712. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  14713. } ).ElseIf( face.equal( 2.0 ), () => {
  14714. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  14715. } ).ElseIf( face.equal( 3.0 ), () => {
  14716. direction.assign( direction.zyx );
  14717. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  14718. } ).ElseIf( face.equal( 4.0 ), () => {
  14719. direction.assign( direction.xzy );
  14720. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  14721. } ).ElseIf( face.equal( 5.0 ), () => {
  14722. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  14723. } );
  14724. return direction;
  14725. } ).setLayout( {
  14726. name: 'getDirection',
  14727. type: 'vec3',
  14728. inputs: [
  14729. { name: 'uv', type: 'vec2' },
  14730. { name: 'face', type: 'float' }
  14731. ]
  14732. } );
  14733. //
  14734. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14735. const roughness = float( roughness_immutable );
  14736. const sampleDir = vec3( sampleDir_immutable );
  14737. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14738. const mipF = fract( mip );
  14739. const mipInt = floor( mip );
  14740. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14741. If( mipF.notEqual( 0.0 ), () => {
  14742. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14743. color0.assign( mix( color0, color1, mipF ) );
  14744. } );
  14745. return color0;
  14746. } );
  14747. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14748. const mipInt = float( mipInt_immutable ).toVar();
  14749. const direction = vec3( direction_immutable );
  14750. const face = float( getFace( direction ) ).toVar();
  14751. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14752. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14753. const faceSize = float( exp2( mipInt ) ).toVar();
  14754. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14755. If( face.greaterThan( 2.0 ), () => {
  14756. uv.y.addAssign( faceSize );
  14757. face.subAssign( 3.0 );
  14758. } );
  14759. uv.x.addAssign( face.mul( faceSize ) );
  14760. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14761. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14762. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14763. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14764. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14765. } );
  14766. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14767. const cosTheta = cos( theta );
  14768. // Rodrigues' axis-angle rotation
  14769. const sampleDirection = outputDirection.mul( cosTheta )
  14770. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14771. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14772. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14773. } );
  14774. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14775. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14776. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14777. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14778. } );
  14779. axis.assign( normalize( axis ) );
  14780. const gl_FragColor = vec3().toVar();
  14781. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14782. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14783. If( i.greaterThanEqual( samples ), () => {
  14784. Break();
  14785. } );
  14786. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14787. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( -1 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14788. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14789. } );
  14790. return vec4( gl_FragColor, 1 );
  14791. } );
  14792. const LOD_MIN = 4;
  14793. // The standard deviations (radians) associated with the extra mips. These are
  14794. // chosen to approximate a Trowbridge-Reitz distribution function times the
  14795. // geometric shadowing function. These sigma values squared must match the
  14796. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  14797. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  14798. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  14799. // samples and exit early, but not recompile the shader.
  14800. const MAX_SAMPLES = 20;
  14801. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  14802. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  14803. const _clearColor$2 = /*@__PURE__*/ new Color();
  14804. let _oldTarget = null;
  14805. let _oldActiveCubeFace = 0;
  14806. let _oldActiveMipmapLevel = 0;
  14807. // Golden Ratio
  14808. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  14809. const INV_PHI = 1 / PHI;
  14810. // Vertices of a dodecahedron (except the opposites, which represent the
  14811. // same axis), used as axis directions evenly spread on a sphere.
  14812. const _axisDirections = [
  14813. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  14814. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  14815. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  14816. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  14817. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  14818. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  14819. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  14820. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  14821. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  14822. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  14823. ];
  14824. const _origin = /*@__PURE__*/ new Vector3();
  14825. // maps blur materials to their uniforms dictionary
  14826. const _uniformsMap = new WeakMap();
  14827. // WebGPU Face indices
  14828. const _faceLib = [
  14829. 3, 1, 5,
  14830. 0, 4, 2
  14831. ];
  14832. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  14833. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  14834. /**
  14835. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  14836. * (PMREM) from a cubeMap environment texture. This allows different levels of
  14837. * blur to be quickly accessed based on material roughness. It is packed into a
  14838. * special CubeUV format that allows us to perform custom interpolation so that
  14839. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  14840. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  14841. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  14842. * higher roughness levels. In this way we maintain resolution to smoothly
  14843. * interpolate diffuse lighting while limiting sampling computation.
  14844. *
  14845. * Paper: Fast, Accurate Image-Based Lighting:
  14846. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  14847. */
  14848. class PMREMGenerator {
  14849. /**
  14850. * Constructs a new PMREM generator.
  14851. *
  14852. * @param {Renderer} renderer - The renderer.
  14853. */
  14854. constructor( renderer ) {
  14855. this._renderer = renderer;
  14856. this._pingPongRenderTarget = null;
  14857. this._lodMax = 0;
  14858. this._cubeSize = 0;
  14859. this._lodPlanes = [];
  14860. this._sizeLods = [];
  14861. this._sigmas = [];
  14862. this._lodMeshes = [];
  14863. this._blurMaterial = null;
  14864. this._cubemapMaterial = null;
  14865. this._equirectMaterial = null;
  14866. this._backgroundBox = null;
  14867. }
  14868. get _hasInitialized() {
  14869. return this._renderer.hasInitialized();
  14870. }
  14871. /**
  14872. * Generates a PMREM from a supplied Scene, which can be faster than using an
  14873. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  14874. * in radians to be applied to the scene before PMREM generation. Optional near
  14875. * and far planes ensure the scene is rendered in its entirety.
  14876. *
  14877. * @param {Scene} scene - The scene to be captured.
  14878. * @param {number} [sigma=0] - The blur radius in radians.
  14879. * @param {number} [near=0.1] - The near plane distance.
  14880. * @param {number} [far=100] - The far plane distance.
  14881. * @param {Object} [options={}] - The configuration options.
  14882. * @param {number} [options.size=256] - The texture size of the PMREM.
  14883. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  14884. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  14885. * @return {RenderTarget} The resulting PMREM.
  14886. * @see {@link PMREMGenerator#fromSceneAsync}
  14887. */
  14888. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  14889. const {
  14890. size = 256,
  14891. position = _origin,
  14892. renderTarget = null,
  14893. } = options;
  14894. this._setSize( size );
  14895. if ( this._hasInitialized === false ) {
  14896. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  14897. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14898. options.renderTarget = cubeUVRenderTarget;
  14899. this.fromSceneAsync( scene, sigma, near, far, options );
  14900. return cubeUVRenderTarget;
  14901. }
  14902. _oldTarget = this._renderer.getRenderTarget();
  14903. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  14904. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  14905. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14906. cubeUVRenderTarget.depthBuffer = true;
  14907. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  14908. if ( sigma > 0 ) {
  14909. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  14910. }
  14911. this._applyPMREM( cubeUVRenderTarget );
  14912. this._cleanup( cubeUVRenderTarget );
  14913. return cubeUVRenderTarget;
  14914. }
  14915. /**
  14916. * Generates a PMREM from a supplied Scene, which can be faster than using an
  14917. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  14918. * in radians to be applied to the scene before PMREM generation. Optional near
  14919. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  14920. * is placed at the origin).
  14921. *
  14922. * @param {Scene} scene - The scene to be captured.
  14923. * @param {number} [sigma=0] - The blur radius in radians.
  14924. * @param {number} [near=0.1] - The near plane distance.
  14925. * @param {number} [far=100] - The far plane distance.
  14926. * @param {Object} [options={}] - The configuration options.
  14927. * @param {number} [options.size=256] - The texture size of the PMREM.
  14928. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  14929. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  14930. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  14931. * @see {@link PMREMGenerator#fromScene}
  14932. */
  14933. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  14934. if ( this._hasInitialized === false ) await this._renderer.init();
  14935. return this.fromScene( scene, sigma, near, far, options );
  14936. }
  14937. /**
  14938. * Generates a PMREM from an equirectangular texture, which can be either LDR
  14939. * or HDR. The ideal input image size is 1k (1024 x 512),
  14940. * as this matches best with the 256 x 256 cubemap output.
  14941. *
  14942. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  14943. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  14944. * @return {RenderTarget} The resulting PMREM.
  14945. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  14946. */
  14947. fromEquirectangular( equirectangular, renderTarget = null ) {
  14948. if ( this._hasInitialized === false ) {
  14949. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  14950. this._setSizeFromTexture( equirectangular );
  14951. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14952. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  14953. return cubeUVRenderTarget;
  14954. }
  14955. return this._fromTexture( equirectangular, renderTarget );
  14956. }
  14957. /**
  14958. * Generates a PMREM from an equirectangular texture, which can be either LDR
  14959. * or HDR. The ideal input image size is 1k (1024 x 512),
  14960. * as this matches best with the 256 x 256 cubemap output.
  14961. *
  14962. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  14963. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  14964. * @return {Promise<RenderTarget>} The resulting PMREM.
  14965. * @see {@link PMREMGenerator#fromEquirectangular}
  14966. */
  14967. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  14968. if ( this._hasInitialized === false ) await this._renderer.init();
  14969. return this._fromTexture( equirectangular, renderTarget );
  14970. }
  14971. /**
  14972. * Generates a PMREM from an cubemap texture, which can be either LDR
  14973. * or HDR. The ideal input cube size is 256 x 256,
  14974. * as this matches best with the 256 x 256 cubemap output.
  14975. *
  14976. * @param {Texture} cubemap - The cubemap texture to be converted.
  14977. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  14978. * @return {RenderTarget} The resulting PMREM.
  14979. * @see {@link PMREMGenerator#fromCubemapAsync}
  14980. */
  14981. fromCubemap( cubemap, renderTarget = null ) {
  14982. if ( this._hasInitialized === false ) {
  14983. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  14984. this._setSizeFromTexture( cubemap );
  14985. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  14986. this.fromCubemapAsync( cubemap, renderTarget );
  14987. return cubeUVRenderTarget;
  14988. }
  14989. return this._fromTexture( cubemap, renderTarget );
  14990. }
  14991. /**
  14992. * Generates a PMREM from an cubemap texture, which can be either LDR
  14993. * or HDR. The ideal input cube size is 256 x 256,
  14994. * with the 256 x 256 cubemap output.
  14995. *
  14996. * @param {Texture} cubemap - The cubemap texture to be converted.
  14997. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  14998. * @return {Promise<RenderTarget>} The resulting PMREM.
  14999. * @see {@link PMREMGenerator#fromCubemap}
  15000. */
  15001. async fromCubemapAsync( cubemap, renderTarget = null ) {
  15002. if ( this._hasInitialized === false ) await this._renderer.init();
  15003. return this._fromTexture( cubemap, renderTarget );
  15004. }
  15005. /**
  15006. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  15007. * your texture's network fetch for increased concurrency.
  15008. *
  15009. * @returns {Promise}
  15010. */
  15011. async compileCubemapShader() {
  15012. if ( this._cubemapMaterial === null ) {
  15013. this._cubemapMaterial = _getCubemapMaterial();
  15014. await this._compileMaterial( this._cubemapMaterial );
  15015. }
  15016. }
  15017. /**
  15018. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  15019. * your texture's network fetch for increased concurrency.
  15020. *
  15021. * @returns {Promise}
  15022. */
  15023. async compileEquirectangularShader() {
  15024. if ( this._equirectMaterial === null ) {
  15025. this._equirectMaterial = _getEquirectMaterial();
  15026. await this._compileMaterial( this._equirectMaterial );
  15027. }
  15028. }
  15029. /**
  15030. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  15031. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  15032. * one of them will cause any others to also become unusable.
  15033. */
  15034. dispose() {
  15035. this._dispose();
  15036. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  15037. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  15038. if ( this._backgroundBox !== null ) {
  15039. this._backgroundBox.geometry.dispose();
  15040. this._backgroundBox.material.dispose();
  15041. }
  15042. }
  15043. // private interface
  15044. _setSizeFromTexture( texture ) {
  15045. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  15046. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  15047. } else { // Equirectangular
  15048. this._setSize( texture.image.width / 4 );
  15049. }
  15050. }
  15051. _setSize( cubeSize ) {
  15052. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  15053. this._cubeSize = Math.pow( 2, this._lodMax );
  15054. }
  15055. _dispose() {
  15056. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  15057. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  15058. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  15059. this._lodPlanes[ i ].dispose();
  15060. }
  15061. }
  15062. _cleanup( outputTarget ) {
  15063. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  15064. outputTarget.scissorTest = false;
  15065. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  15066. }
  15067. _fromTexture( texture, renderTarget ) {
  15068. this._setSizeFromTexture( texture );
  15069. _oldTarget = this._renderer.getRenderTarget();
  15070. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  15071. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  15072. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15073. this._textureToCubeUV( texture, cubeUVRenderTarget );
  15074. this._applyPMREM( cubeUVRenderTarget );
  15075. this._cleanup( cubeUVRenderTarget );
  15076. return cubeUVRenderTarget;
  15077. }
  15078. _allocateTargets() {
  15079. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  15080. const height = 4 * this._cubeSize;
  15081. const params = {
  15082. magFilter: LinearFilter,
  15083. minFilter: LinearFilter,
  15084. generateMipmaps: false,
  15085. type: HalfFloatType,
  15086. format: RGBAFormat,
  15087. colorSpace: LinearSRGBColorSpace,
  15088. //depthBuffer: false
  15089. };
  15090. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  15091. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  15092. if ( this._pingPongRenderTarget !== null ) {
  15093. this._dispose();
  15094. }
  15095. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  15096. const { _lodMax } = this;
  15097. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  15098. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  15099. }
  15100. return cubeUVRenderTarget;
  15101. }
  15102. async _compileMaterial( material ) {
  15103. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  15104. await this._renderer.compile( tmpMesh, _flatCamera );
  15105. }
  15106. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  15107. const cubeCamera = _cubeCamera;
  15108. cubeCamera.near = near;
  15109. cubeCamera.far = far;
  15110. // px, py, pz, nx, ny, nz
  15111. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  15112. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  15113. const renderer = this._renderer;
  15114. const originalAutoClear = renderer.autoClear;
  15115. renderer.getClearColor( _clearColor$2 );
  15116. renderer.autoClear = false;
  15117. let backgroundBox = this._backgroundBox;
  15118. if ( backgroundBox === null ) {
  15119. const backgroundMaterial = new MeshBasicMaterial( {
  15120. name: 'PMREM.Background',
  15121. side: BackSide,
  15122. depthWrite: false,
  15123. depthTest: false
  15124. } );
  15125. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  15126. }
  15127. let useSolidColor = false;
  15128. const background = scene.background;
  15129. if ( background ) {
  15130. if ( background.isColor ) {
  15131. backgroundBox.material.color.copy( background );
  15132. scene.background = null;
  15133. useSolidColor = true;
  15134. }
  15135. } else {
  15136. backgroundBox.material.color.copy( _clearColor$2 );
  15137. useSolidColor = true;
  15138. }
  15139. renderer.setRenderTarget( cubeUVRenderTarget );
  15140. renderer.clear();
  15141. if ( useSolidColor ) {
  15142. renderer.render( backgroundBox, cubeCamera );
  15143. }
  15144. for ( let i = 0; i < 6; i ++ ) {
  15145. const col = i % 3;
  15146. if ( col === 0 ) {
  15147. cubeCamera.up.set( 0, upSign[ i ], 0 );
  15148. cubeCamera.position.set( position.x, position.y, position.z );
  15149. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  15150. } else if ( col === 1 ) {
  15151. cubeCamera.up.set( 0, 0, upSign[ i ] );
  15152. cubeCamera.position.set( position.x, position.y, position.z );
  15153. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  15154. } else {
  15155. cubeCamera.up.set( 0, upSign[ i ], 0 );
  15156. cubeCamera.position.set( position.x, position.y, position.z );
  15157. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  15158. }
  15159. const size = this._cubeSize;
  15160. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  15161. renderer.render( scene, cubeCamera );
  15162. }
  15163. renderer.autoClear = originalAutoClear;
  15164. scene.background = background;
  15165. }
  15166. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  15167. const renderer = this._renderer;
  15168. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  15169. if ( isCubeTexture ) {
  15170. if ( this._cubemapMaterial === null ) {
  15171. this._cubemapMaterial = _getCubemapMaterial( texture );
  15172. }
  15173. } else {
  15174. if ( this._equirectMaterial === null ) {
  15175. this._equirectMaterial = _getEquirectMaterial( texture );
  15176. }
  15177. }
  15178. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  15179. material.fragmentNode.value = texture;
  15180. const mesh = this._lodMeshes[ 0 ];
  15181. mesh.material = material;
  15182. const size = this._cubeSize;
  15183. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  15184. renderer.setRenderTarget( cubeUVRenderTarget );
  15185. renderer.render( mesh, _flatCamera );
  15186. }
  15187. _applyPMREM( cubeUVRenderTarget ) {
  15188. const renderer = this._renderer;
  15189. const autoClear = renderer.autoClear;
  15190. renderer.autoClear = false;
  15191. const n = this._lodPlanes.length;
  15192. for ( let i = 1; i < n; i ++ ) {
  15193. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  15194. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  15195. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  15196. }
  15197. renderer.autoClear = autoClear;
  15198. }
  15199. /**
  15200. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  15201. * vertically and horizontally, but this breaks down on a cube. Here we apply
  15202. * the blur latitudinally (around the poles), and then longitudinally (towards
  15203. * the poles) to approximate the orthogonally-separable blur. It is least
  15204. * accurate at the poles, but still does a decent job.
  15205. *
  15206. * @private
  15207. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  15208. * @param {number} lodIn - The input level-of-detail.
  15209. * @param {number} lodOut - The output level-of-detail.
  15210. * @param {number} sigma - The blur radius in radians.
  15211. * @param {Vector3} [poleAxis] - The pole axis.
  15212. */
  15213. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  15214. const pingPongRenderTarget = this._pingPongRenderTarget;
  15215. this._halfBlur(
  15216. cubeUVRenderTarget,
  15217. pingPongRenderTarget,
  15218. lodIn,
  15219. lodOut,
  15220. sigma,
  15221. 'latitudinal',
  15222. poleAxis );
  15223. this._halfBlur(
  15224. pingPongRenderTarget,
  15225. cubeUVRenderTarget,
  15226. lodOut,
  15227. lodOut,
  15228. sigma,
  15229. 'longitudinal',
  15230. poleAxis );
  15231. }
  15232. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  15233. const renderer = this._renderer;
  15234. const blurMaterial = this._blurMaterial;
  15235. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  15236. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  15237. }
  15238. // Number of standard deviations at which to cut off the discrete approximation.
  15239. const STANDARD_DEVIATIONS = 3;
  15240. const blurMesh = this._lodMeshes[ lodOut ];
  15241. blurMesh.material = blurMaterial;
  15242. const blurUniforms = _uniformsMap.get( blurMaterial );
  15243. const pixels = this._sizeLods[ lodIn ] - 1;
  15244. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  15245. const sigmaPixels = sigmaRadians / radiansPerPixel;
  15246. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  15247. if ( samples > MAX_SAMPLES ) {
  15248. console.warn( `sigmaRadians, ${
  15249. sigmaRadians}, is too large and will clip, as it requested ${
  15250. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  15251. }
  15252. const weights = [];
  15253. let sum = 0;
  15254. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  15255. const x = i / sigmaPixels;
  15256. const weight = Math.exp( - x * x / 2 );
  15257. weights.push( weight );
  15258. if ( i === 0 ) {
  15259. sum += weight;
  15260. } else if ( i < samples ) {
  15261. sum += 2 * weight;
  15262. }
  15263. }
  15264. for ( let i = 0; i < weights.length; i ++ ) {
  15265. weights[ i ] = weights[ i ] / sum;
  15266. }
  15267. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  15268. blurUniforms.envMap.value = targetIn.texture;
  15269. blurUniforms.samples.value = samples;
  15270. blurUniforms.weights.array = weights;
  15271. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  15272. if ( poleAxis ) {
  15273. blurUniforms.poleAxis.value = poleAxis;
  15274. }
  15275. const { _lodMax } = this;
  15276. blurUniforms.dTheta.value = radiansPerPixel;
  15277. blurUniforms.mipInt.value = _lodMax - lodIn;
  15278. const outputSize = this._sizeLods[ lodOut ];
  15279. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  15280. const y = 4 * ( this._cubeSize - outputSize );
  15281. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  15282. renderer.setRenderTarget( targetOut );
  15283. renderer.render( blurMesh, _flatCamera );
  15284. }
  15285. }
  15286. function _createPlanes( lodMax ) {
  15287. const lodPlanes = [];
  15288. const sizeLods = [];
  15289. const sigmas = [];
  15290. const lodMeshes = [];
  15291. let lod = lodMax;
  15292. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  15293. for ( let i = 0; i < totalLods; i ++ ) {
  15294. const sizeLod = Math.pow( 2, lod );
  15295. sizeLods.push( sizeLod );
  15296. let sigma = 1.0 / sizeLod;
  15297. if ( i > lodMax - LOD_MIN ) {
  15298. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  15299. } else if ( i === 0 ) {
  15300. sigma = 0;
  15301. }
  15302. sigmas.push( sigma );
  15303. const texelSize = 1.0 / ( sizeLod - 2 );
  15304. const min = - texelSize;
  15305. const max = 1 + texelSize;
  15306. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  15307. const cubeFaces = 6;
  15308. const vertices = 6;
  15309. const positionSize = 3;
  15310. const uvSize = 2;
  15311. const faceIndexSize = 1;
  15312. const position = new Float32Array( positionSize * vertices * cubeFaces );
  15313. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  15314. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  15315. for ( let face = 0; face < cubeFaces; face ++ ) {
  15316. const x = ( face % 3 ) * 2 / 3 - 1;
  15317. const y = face > 2 ? 0 : -1;
  15318. const coordinates = [
  15319. x, y, 0,
  15320. x + 2 / 3, y, 0,
  15321. x + 2 / 3, y + 1, 0,
  15322. x, y, 0,
  15323. x + 2 / 3, y + 1, 0,
  15324. x, y + 1, 0
  15325. ];
  15326. const faceIdx = _faceLib[ face ];
  15327. position.set( coordinates, positionSize * vertices * faceIdx );
  15328. uv.set( uv1, uvSize * vertices * faceIdx );
  15329. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  15330. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  15331. }
  15332. const planes = new BufferGeometry();
  15333. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  15334. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  15335. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  15336. lodPlanes.push( planes );
  15337. lodMeshes.push( new Mesh( planes, null ) );
  15338. if ( lod > LOD_MIN ) {
  15339. lod --;
  15340. }
  15341. }
  15342. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  15343. }
  15344. function _createRenderTarget( width, height, params ) {
  15345. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  15346. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  15347. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  15348. cubeUVRenderTarget.texture.isPMREMTexture = true;
  15349. cubeUVRenderTarget.scissorTest = true;
  15350. return cubeUVRenderTarget;
  15351. }
  15352. function _setViewport( target, x, y, width, height ) {
  15353. target.viewport.set( x, y, width, height );
  15354. target.scissor.set( x, y, width, height );
  15355. }
  15356. function _getMaterial( type ) {
  15357. const material = new NodeMaterial();
  15358. material.depthTest = false;
  15359. material.depthWrite = false;
  15360. material.blending = NoBlending;
  15361. material.name = `PMREM_${ type }`;
  15362. return material;
  15363. }
  15364. function _getBlurShader( lodMax, width, height ) {
  15365. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  15366. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  15367. const dTheta = uniform( 0 );
  15368. const n = float( MAX_SAMPLES );
  15369. const latitudinal = uniform( 0 ); // false, bool
  15370. const samples = uniform( 1 ); // int
  15371. const envMap = texture( null );
  15372. const mipInt = uniform( 0 ); // int
  15373. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  15374. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  15375. const CUBEUV_MAX_MIP = float( lodMax );
  15376. const materialUniforms = {
  15377. n,
  15378. latitudinal,
  15379. weights,
  15380. poleAxis,
  15381. outputDirection: _outputDirection,
  15382. dTheta,
  15383. samples,
  15384. envMap,
  15385. mipInt,
  15386. CUBEUV_TEXEL_WIDTH,
  15387. CUBEUV_TEXEL_HEIGHT,
  15388. CUBEUV_MAX_MIP
  15389. };
  15390. const material = _getMaterial( 'blur' );
  15391. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  15392. _uniformsMap.set( material, materialUniforms );
  15393. return material;
  15394. }
  15395. function _getCubemapMaterial( envTexture ) {
  15396. const material = _getMaterial( 'cubemap' );
  15397. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  15398. return material;
  15399. }
  15400. function _getEquirectMaterial( envTexture ) {
  15401. const material = _getMaterial( 'equirect' );
  15402. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  15403. return material;
  15404. }
  15405. const _cache = new WeakMap();
  15406. /**
  15407. * Generates the cubeUV size based on the given image height.
  15408. *
  15409. * @private
  15410. * @param {number} imageHeight - The image height.
  15411. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  15412. */
  15413. function _generateCubeUVSize( imageHeight ) {
  15414. const maxMip = Math.log2( imageHeight ) - 2;
  15415. const texelHeight = 1.0 / imageHeight;
  15416. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  15417. return { texelWidth, texelHeight, maxMip };
  15418. }
  15419. /**
  15420. * Generates a PMREM from the given texture.
  15421. *
  15422. * @private
  15423. * @param {Texture} texture - The texture to create the PMREM for.
  15424. * @param {Renderer} renderer - The renderer.
  15425. * @param {PMREMGenerator} generator - The PMREM generator.
  15426. * @return {?Texture} The PMREM.
  15427. */
  15428. function _getPMREMFromTexture( texture, renderer, generator ) {
  15429. const cache = _getCache( renderer );
  15430. let cacheTexture = cache.get( texture );
  15431. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  15432. if ( pmremVersion !== texture.pmremVersion ) {
  15433. const image = texture.image;
  15434. if ( texture.isCubeTexture ) {
  15435. if ( isCubeMapReady( image ) ) {
  15436. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  15437. } else {
  15438. return null;
  15439. }
  15440. } else {
  15441. if ( isEquirectangularMapReady( image ) ) {
  15442. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  15443. } else {
  15444. return null;
  15445. }
  15446. }
  15447. cacheTexture.pmremVersion = texture.pmremVersion;
  15448. cache.set( texture, cacheTexture );
  15449. }
  15450. return cacheTexture.texture;
  15451. }
  15452. /**
  15453. * Returns a cache that stores generated PMREMs for the respective textures.
  15454. * A cache must be maintained per renderer since PMREMs are render target textures
  15455. * which can't be shared across render contexts.
  15456. *
  15457. * @private
  15458. * @param {Renderer} renderer - The renderer.
  15459. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  15460. */
  15461. function _getCache( renderer ) {
  15462. let rendererCache = _cache.get( renderer );
  15463. if ( rendererCache === undefined ) {
  15464. rendererCache = new WeakMap();
  15465. _cache.set( renderer, rendererCache );
  15466. }
  15467. return rendererCache;
  15468. }
  15469. /**
  15470. * This node represents a PMREM which is a special type of preprocessed
  15471. * environment map intended for PBR materials.
  15472. *
  15473. * ```js
  15474. * const material = new MeshStandardNodeMaterial();
  15475. * material.envNode = pmremTexture( envMap );
  15476. * ```
  15477. *
  15478. * @augments TempNode
  15479. */
  15480. class PMREMNode extends TempNode {
  15481. static get type() {
  15482. return 'PMREMNode';
  15483. }
  15484. /**
  15485. * Constructs a new function overloading node.
  15486. *
  15487. * @param {Texture} value - The input texture.
  15488. * @param {Node<vec2>} [uvNode=null] - The uv node.
  15489. * @param {Node<float>} [levelNode=null] - The level node.
  15490. */
  15491. constructor( value, uvNode = null, levelNode = null ) {
  15492. super( 'vec3' );
  15493. /**
  15494. * Reference to the input texture.
  15495. *
  15496. * @private
  15497. * @type {Texture}
  15498. */
  15499. this._value = value;
  15500. /**
  15501. * Reference to the generated PMREM.
  15502. *
  15503. * @private
  15504. * @type {Texture | null}
  15505. * @default null
  15506. */
  15507. this._pmrem = null;
  15508. /**
  15509. * The uv node.
  15510. *
  15511. * @type {Node<vec2>}
  15512. */
  15513. this.uvNode = uvNode;
  15514. /**
  15515. * The level node.
  15516. *
  15517. * @type {Node<float>}
  15518. */
  15519. this.levelNode = levelNode;
  15520. /**
  15521. * Reference to a PMREM generator.
  15522. *
  15523. * @private
  15524. * @type {?PMREMGenerator}
  15525. * @default null
  15526. */
  15527. this._generator = null;
  15528. const defaultTexture = new Texture();
  15529. defaultTexture.isRenderTargetTexture = true;
  15530. /**
  15531. * The texture node holding the generated PMREM.
  15532. *
  15533. * @private
  15534. * @type {TextureNode}
  15535. */
  15536. this._texture = texture( defaultTexture );
  15537. /**
  15538. * A uniform representing the PMREM's width.
  15539. *
  15540. * @private
  15541. * @type {UniformNode<float>}
  15542. */
  15543. this._width = uniform( 0 );
  15544. /**
  15545. * A uniform representing the PMREM's height.
  15546. *
  15547. * @private
  15548. * @type {UniformNode<float>}
  15549. */
  15550. this._height = uniform( 0 );
  15551. /**
  15552. * A uniform representing the PMREM's max Mip.
  15553. *
  15554. * @private
  15555. * @type {UniformNode<float>}
  15556. */
  15557. this._maxMip = uniform( 0 );
  15558. /**
  15559. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  15560. *
  15561. * @type {string}
  15562. * @default 'render'
  15563. */
  15564. this.updateBeforeType = NodeUpdateType.RENDER;
  15565. }
  15566. set value( value ) {
  15567. this._value = value;
  15568. this._pmrem = null;
  15569. }
  15570. /**
  15571. * The node's texture value.
  15572. *
  15573. * @type {Texture}
  15574. */
  15575. get value() {
  15576. return this._value;
  15577. }
  15578. /**
  15579. * Uses the given PMREM texture to update internal values.
  15580. *
  15581. * @param {Texture} texture - The PMREM texture.
  15582. */
  15583. updateFromTexture( texture ) {
  15584. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  15585. this._texture.value = texture;
  15586. this._width.value = cubeUVSize.texelWidth;
  15587. this._height.value = cubeUVSize.texelHeight;
  15588. this._maxMip.value = cubeUVSize.maxMip;
  15589. }
  15590. updateBefore( frame ) {
  15591. let pmrem = this._pmrem;
  15592. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  15593. const texture = this._value;
  15594. if ( pmremVersion !== texture.pmremVersion ) {
  15595. if ( texture.isPMREMTexture === true ) {
  15596. pmrem = texture;
  15597. } else {
  15598. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  15599. }
  15600. if ( pmrem !== null ) {
  15601. this._pmrem = pmrem;
  15602. this.updateFromTexture( pmrem );
  15603. }
  15604. }
  15605. }
  15606. setup( builder ) {
  15607. if ( this._generator === null ) {
  15608. this._generator = new PMREMGenerator( builder.renderer );
  15609. }
  15610. this.updateBefore( builder );
  15611. //
  15612. let uvNode = this.uvNode;
  15613. if ( uvNode === null && builder.context.getUV ) {
  15614. uvNode = builder.context.getUV( this );
  15615. }
  15616. //
  15617. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  15618. //
  15619. let levelNode = this.levelNode;
  15620. if ( levelNode === null && builder.context.getTextureLevel ) {
  15621. levelNode = builder.context.getTextureLevel( this );
  15622. }
  15623. //
  15624. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  15625. }
  15626. dispose() {
  15627. super.dispose();
  15628. if ( this._generator !== null ) this._generator.dispose();
  15629. }
  15630. }
  15631. /**
  15632. * Returns `true` if the given cube map image has been fully loaded.
  15633. *
  15634. * @private
  15635. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  15636. * @return {boolean} Whether the given cube map is ready or not.
  15637. */
  15638. function isCubeMapReady( image ) {
  15639. if ( image === null || image === undefined ) return false;
  15640. let count = 0;
  15641. const length = 6;
  15642. for ( let i = 0; i < length; i ++ ) {
  15643. if ( image[ i ] !== undefined ) count ++;
  15644. }
  15645. return count === length;
  15646. }
  15647. /**
  15648. * Returns `true` if the given equirectangular image has been fully loaded.
  15649. *
  15650. * @private
  15651. * @param {(Image|Object)} image - The equirectangular image.
  15652. * @return {boolean} Whether the given cube map is ready or not.
  15653. */
  15654. function isEquirectangularMapReady( image ) {
  15655. if ( image === null || image === undefined ) return false;
  15656. return image.height > 0;
  15657. }
  15658. /**
  15659. * TSL function for creating a PMREM node.
  15660. *
  15661. * @tsl
  15662. * @function
  15663. * @param {Texture} value - The input texture.
  15664. * @param {Node<vec2>} [uvNode=null] - The uv node.
  15665. * @param {Node<float>} [levelNode=null] - The level node.
  15666. * @returns {PMREMNode}
  15667. */
  15668. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  15669. const _envNodeCache = new WeakMap();
  15670. /**
  15671. * Represents a physical model for Image-based lighting (IBL). The environment
  15672. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  15673. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  15674. *
  15675. * @augments LightingNode
  15676. */
  15677. class EnvironmentNode extends LightingNode {
  15678. static get type() {
  15679. return 'EnvironmentNode';
  15680. }
  15681. /**
  15682. * Constructs a new environment node.
  15683. *
  15684. * @param {Node} [envNode=null] - A node representing the environment.
  15685. */
  15686. constructor( envNode = null ) {
  15687. super();
  15688. /**
  15689. * A node representing the environment.
  15690. *
  15691. * @type {?Node}
  15692. * @default null
  15693. */
  15694. this.envNode = envNode;
  15695. }
  15696. setup( builder ) {
  15697. const { material } = builder;
  15698. let envNode = this.envNode;
  15699. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15700. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15701. let cacheEnvNode = _envNodeCache.get( value );
  15702. if ( cacheEnvNode === undefined ) {
  15703. cacheEnvNode = pmremTexture( value );
  15704. _envNodeCache.set( value, cacheEnvNode );
  15705. }
  15706. envNode = cacheEnvNode;
  15707. }
  15708. //
  15709. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  15710. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  15711. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  15712. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  15713. const isolateRadiance = cache( radiance );
  15714. const isolateIrradiance = cache( irradiance );
  15715. //
  15716. builder.context.radiance.addAssign( isolateRadiance );
  15717. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  15718. //
  15719. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  15720. if ( clearcoatRadiance ) {
  15721. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( materialEnvIntensity );
  15722. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  15723. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  15724. }
  15725. }
  15726. }
  15727. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  15728. let reflectVec = null;
  15729. return {
  15730. getUV: () => {
  15731. if ( reflectVec === null ) {
  15732. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  15733. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  15734. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  15735. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  15736. }
  15737. return reflectVec;
  15738. },
  15739. getTextureLevel: () => {
  15740. return roughnessNode;
  15741. }
  15742. };
  15743. };
  15744. const createIrradianceContext = ( normalWorldNode ) => {
  15745. return {
  15746. getUV: () => {
  15747. return normalWorldNode;
  15748. },
  15749. getTextureLevel: () => {
  15750. return float( 1.0 );
  15751. }
  15752. };
  15753. };
  15754. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  15755. /**
  15756. * Node material version of {@link MeshStandardMaterial}.
  15757. *
  15758. * @augments NodeMaterial
  15759. */
  15760. class MeshStandardNodeMaterial extends NodeMaterial {
  15761. static get type() {
  15762. return 'MeshStandardNodeMaterial';
  15763. }
  15764. /**
  15765. * Constructs a new mesh standard node material.
  15766. *
  15767. * @param {Object} [parameters] - The configuration parameter.
  15768. */
  15769. constructor( parameters ) {
  15770. super();
  15771. /**
  15772. * This flag can be used for type testing.
  15773. *
  15774. * @type {boolean}
  15775. * @readonly
  15776. * @default true
  15777. */
  15778. this.isMeshStandardNodeMaterial = true;
  15779. /**
  15780. * Set to `true` because standard materials react on lights.
  15781. *
  15782. * @type {boolean}
  15783. * @default true
  15784. */
  15785. this.lights = true;
  15786. /**
  15787. * The emissive color of standard materials is by default inferred from the `emissive`,
  15788. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  15789. * overwrite the default and define the emissive color with a node instead.
  15790. *
  15791. * If you don't want to overwrite the emissive color but modify the existing
  15792. * value instead, use {@link materialEmissive}.
  15793. *
  15794. * @type {?Node<vec3>}
  15795. * @default null
  15796. */
  15797. this.emissiveNode = null;
  15798. /**
  15799. * The metalness of standard materials is by default inferred from the `metalness`,
  15800. * and `metalnessMap` properties. This node property allows to
  15801. * overwrite the default and define the metalness with a node instead.
  15802. *
  15803. * If you don't want to overwrite the metalness but modify the existing
  15804. * value instead, use {@link materialMetalness}.
  15805. *
  15806. * @type {?Node<float>}
  15807. * @default null
  15808. */
  15809. this.metalnessNode = null;
  15810. /**
  15811. * The roughness of standard materials is by default inferred from the `roughness`,
  15812. * and `roughnessMap` properties. This node property allows to
  15813. * overwrite the default and define the roughness with a node instead.
  15814. *
  15815. * If you don't want to overwrite the roughness but modify the existing
  15816. * value instead, use {@link materialRoughness}.
  15817. *
  15818. * @type {?Node<float>}
  15819. * @default null
  15820. */
  15821. this.roughnessNode = null;
  15822. this.setDefaultValues( _defaultValues$6 );
  15823. this.setValues( parameters );
  15824. }
  15825. /**
  15826. * Overwritten since this type of material uses {@link EnvironmentNode}
  15827. * to implement the PBR (PMREM based) environment mapping. Besides, the
  15828. * method honors `Scene.environment`.
  15829. *
  15830. * @param {NodeBuilder} builder - The current node builder.
  15831. * @return {?EnvironmentNode<vec3>} The environment node.
  15832. */
  15833. setupEnvironment( builder ) {
  15834. let envNode = super.setupEnvironment( builder );
  15835. if ( envNode === null && builder.environmentNode ) {
  15836. envNode = builder.environmentNode;
  15837. }
  15838. return envNode ? new EnvironmentNode( envNode ) : null;
  15839. }
  15840. /**
  15841. * Setups the lighting model.
  15842. *
  15843. * @return {PhysicalLightingModel} The lighting model.
  15844. */
  15845. setupLightingModel( /*builder*/ ) {
  15846. return new PhysicalLightingModel();
  15847. }
  15848. /**
  15849. * Setups the specular related node variables.
  15850. */
  15851. setupSpecular() {
  15852. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  15853. specularColor.assign( specularColorNode );
  15854. specularF90.assign( 1.0 );
  15855. }
  15856. /**
  15857. * Setups the standard specific node variables.
  15858. *
  15859. * @param {NodeBuilder} builder - The current node builder.
  15860. */
  15861. setupVariants() {
  15862. // METALNESS
  15863. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  15864. metalness.assign( metalnessNode );
  15865. // ROUGHNESS
  15866. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  15867. roughnessNode = getRoughness( { roughness: roughnessNode } );
  15868. roughness.assign( roughnessNode );
  15869. // SPECULAR COLOR
  15870. this.setupSpecular();
  15871. // DIFFUSE COLOR
  15872. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  15873. }
  15874. copy( source ) {
  15875. this.emissiveNode = source.emissiveNode;
  15876. this.metalnessNode = source.metalnessNode;
  15877. this.roughnessNode = source.roughnessNode;
  15878. return super.copy( source );
  15879. }
  15880. }
  15881. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  15882. /**
  15883. * Node material version of {@link MeshPhysicalMaterial}.
  15884. *
  15885. * @augments MeshStandardNodeMaterial
  15886. */
  15887. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  15888. static get type() {
  15889. return 'MeshPhysicalNodeMaterial';
  15890. }
  15891. /**
  15892. * Constructs a new mesh physical node material.
  15893. *
  15894. * @param {Object} [parameters] - The configuration parameter.
  15895. */
  15896. constructor( parameters ) {
  15897. super();
  15898. /**
  15899. * This flag can be used for type testing.
  15900. *
  15901. * @type {boolean}
  15902. * @readonly
  15903. * @default true
  15904. */
  15905. this.isMeshPhysicalNodeMaterial = true;
  15906. /**
  15907. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  15908. * and `clearcoatMap` properties. This node property allows to overwrite the default
  15909. * and define the clearcoat with a node instead.
  15910. *
  15911. * If you don't want to overwrite the clearcoat but modify the existing
  15912. * value instead, use {@link materialClearcoat}.
  15913. *
  15914. * @type {?Node<float>}
  15915. * @default null
  15916. */
  15917. this.clearcoatNode = null;
  15918. /**
  15919. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  15920. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  15921. * and define the clearcoat roughness with a node instead.
  15922. *
  15923. * If you don't want to overwrite the clearcoat roughness but modify the existing
  15924. * value instead, use {@link materialClearcoatRoughness}.
  15925. *
  15926. * @type {?Node<float>}
  15927. * @default null
  15928. */
  15929. this.clearcoatRoughnessNode = null;
  15930. /**
  15931. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  15932. * property. This node property allows to overwrite the default
  15933. * and define the clearcoat normal with a node instead.
  15934. *
  15935. * If you don't want to overwrite the clearcoat normal but modify the existing
  15936. * value instead, use {@link materialClearcoatNormal}.
  15937. *
  15938. * @type {?Node<vec3>}
  15939. * @default null
  15940. */
  15941. this.clearcoatNormalNode = null;
  15942. /**
  15943. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  15944. * and `sheenColorMap` properties. This node property allows to overwrite the default
  15945. * and define the sheen with a node instead.
  15946. *
  15947. * If you don't want to overwrite the sheen but modify the existing
  15948. * value instead, use {@link materialSheen}.
  15949. *
  15950. * @type {?Node<vec3>}
  15951. * @default null
  15952. */
  15953. this.sheenNode = null;
  15954. /**
  15955. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  15956. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  15957. * and define the sheen roughness with a node instead.
  15958. *
  15959. * If you don't want to overwrite the sheen roughness but modify the existing
  15960. * value instead, use {@link materialSheenRoughness}.
  15961. *
  15962. * @type {?Node<float>}
  15963. * @default null
  15964. */
  15965. this.sheenRoughnessNode = null;
  15966. /**
  15967. * The iridescence of physical materials is by default inferred from the `iridescence`
  15968. * property. This node property allows to overwrite the default
  15969. * and define the iridescence with a node instead.
  15970. *
  15971. * If you don't want to overwrite the iridescence but modify the existing
  15972. * value instead, use {@link materialIridescence}.
  15973. *
  15974. * @type {?Node<float>}
  15975. * @default null
  15976. */
  15977. this.iridescenceNode = null;
  15978. /**
  15979. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  15980. * property. This node property allows to overwrite the default
  15981. * and define the iridescence IOR with a node instead.
  15982. *
  15983. * If you don't want to overwrite the iridescence IOR but modify the existing
  15984. * value instead, use {@link materialIridescenceIOR}.
  15985. *
  15986. * @type {?Node<float>}
  15987. * @default null
  15988. */
  15989. this.iridescenceIORNode = null;
  15990. /**
  15991. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  15992. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  15993. * and define the iridescence thickness with a node instead.
  15994. *
  15995. * If you don't want to overwrite the iridescence thickness but modify the existing
  15996. * value instead, use {@link materialIridescenceThickness}.
  15997. *
  15998. * @type {?Node<float>}
  15999. * @default null
  16000. */
  16001. this.iridescenceThicknessNode = null;
  16002. /**
  16003. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  16004. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  16005. * and define the specular intensity with a node instead.
  16006. *
  16007. * If you don't want to overwrite the specular intensity but modify the existing
  16008. * value instead, use {@link materialSpecularIntensity}.
  16009. *
  16010. * @type {?Node<float>}
  16011. * @default null
  16012. */
  16013. this.specularIntensityNode = null;
  16014. /**
  16015. * The specular color of physical materials is by default inferred from the `specularColor`
  16016. * and `specularColorMap` properties. This node property allows to overwrite the default
  16017. * and define the specular color with a node instead.
  16018. *
  16019. * If you don't want to overwrite the specular color but modify the existing
  16020. * value instead, use {@link materialSpecularColor}.
  16021. *
  16022. * @type {?Node<vec3>}
  16023. * @default null
  16024. */
  16025. this.specularColorNode = null;
  16026. /**
  16027. * The ior of physical materials is by default inferred from the `ior`
  16028. * property. This node property allows to overwrite the default
  16029. * and define the ior with a node instead.
  16030. *
  16031. * If you don't want to overwrite the ior but modify the existing
  16032. * value instead, use {@link materialIOR}.
  16033. *
  16034. * @type {?Node<float>}
  16035. * @default null
  16036. */
  16037. this.iorNode = null;
  16038. /**
  16039. * The transmission of physical materials is by default inferred from the `transmission` and
  16040. * `transmissionMap` properties. This node property allows to overwrite the default
  16041. * and define the transmission with a node instead.
  16042. *
  16043. * If you don't want to overwrite the transmission but modify the existing
  16044. * value instead, use {@link materialTransmission}.
  16045. *
  16046. * @type {?Node<float>}
  16047. * @default null
  16048. */
  16049. this.transmissionNode = null;
  16050. /**
  16051. * The thickness of physical materials is by default inferred from the `thickness` and
  16052. * `thicknessMap` properties. This node property allows to overwrite the default
  16053. * and define the thickness with a node instead.
  16054. *
  16055. * If you don't want to overwrite the thickness but modify the existing
  16056. * value instead, use {@link materialThickness}.
  16057. *
  16058. * @type {?Node<float>}
  16059. * @default null
  16060. */
  16061. this.thicknessNode = null;
  16062. /**
  16063. * The attenuation distance of physical materials is by default inferred from the
  16064. * `attenuationDistance` property. This node property allows to overwrite the default
  16065. * and define the attenuation distance with a node instead.
  16066. *
  16067. * If you don't want to overwrite the attenuation distance but modify the existing
  16068. * value instead, use {@link materialAttenuationDistance}.
  16069. *
  16070. * @type {?Node<float>}
  16071. * @default null
  16072. */
  16073. this.attenuationDistanceNode = null;
  16074. /**
  16075. * The attenuation color of physical materials is by default inferred from the
  16076. * `attenuationColor` property. This node property allows to overwrite the default
  16077. * and define the attenuation color with a node instead.
  16078. *
  16079. * If you don't want to overwrite the attenuation color but modify the existing
  16080. * value instead, use {@link materialAttenuationColor}.
  16081. *
  16082. * @type {?Node<vec3>}
  16083. * @default null
  16084. */
  16085. this.attenuationColorNode = null;
  16086. /**
  16087. * The dispersion of physical materials is by default inferred from the
  16088. * `dispersion` property. This node property allows to overwrite the default
  16089. * and define the dispersion with a node instead.
  16090. *
  16091. * If you don't want to overwrite the dispersion but modify the existing
  16092. * value instead, use {@link materialDispersion}.
  16093. *
  16094. * @type {?Node<float>}
  16095. * @default null
  16096. */
  16097. this.dispersionNode = null;
  16098. /**
  16099. * The anisotropy of physical materials is by default inferred from the
  16100. * `anisotropy` property. This node property allows to overwrite the default
  16101. * and define the anisotropy with a node instead.
  16102. *
  16103. * If you don't want to overwrite the anisotropy but modify the existing
  16104. * value instead, use {@link materialAnisotropy}.
  16105. *
  16106. * @type {?Node<float>}
  16107. * @default null
  16108. */
  16109. this.anisotropyNode = null;
  16110. this.setDefaultValues( _defaultValues$5 );
  16111. this.setValues( parameters );
  16112. }
  16113. /**
  16114. * Whether the lighting model should use clearcoat or not.
  16115. *
  16116. * @type {boolean}
  16117. * @default true
  16118. */
  16119. get useClearcoat() {
  16120. return this.clearcoat > 0 || this.clearcoatNode !== null;
  16121. }
  16122. /**
  16123. * Whether the lighting model should use iridescence or not.
  16124. *
  16125. * @type {boolean}
  16126. * @default true
  16127. */
  16128. get useIridescence() {
  16129. return this.iridescence > 0 || this.iridescenceNode !== null;
  16130. }
  16131. /**
  16132. * Whether the lighting model should use sheen or not.
  16133. *
  16134. * @type {boolean}
  16135. * @default true
  16136. */
  16137. get useSheen() {
  16138. return this.sheen > 0 || this.sheenNode !== null;
  16139. }
  16140. /**
  16141. * Whether the lighting model should use anisotropy or not.
  16142. *
  16143. * @type {boolean}
  16144. * @default true
  16145. */
  16146. get useAnisotropy() {
  16147. return this.anisotropy > 0 || this.anisotropyNode !== null;
  16148. }
  16149. /**
  16150. * Whether the lighting model should use transmission or not.
  16151. *
  16152. * @type {boolean}
  16153. * @default true
  16154. */
  16155. get useTransmission() {
  16156. return this.transmission > 0 || this.transmissionNode !== null;
  16157. }
  16158. /**
  16159. * Whether the lighting model should use dispersion or not.
  16160. *
  16161. * @type {boolean}
  16162. * @default true
  16163. */
  16164. get useDispersion() {
  16165. return this.dispersion > 0 || this.dispersionNode !== null;
  16166. }
  16167. /**
  16168. * Setups the specular related node variables.
  16169. */
  16170. setupSpecular() {
  16171. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  16172. ior.assign( iorNode );
  16173. 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 ) );
  16174. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  16175. }
  16176. /**
  16177. * Setups the lighting model.
  16178. *
  16179. * @return {PhysicalLightingModel} The lighting model.
  16180. */
  16181. setupLightingModel( /*builder*/ ) {
  16182. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  16183. }
  16184. /**
  16185. * Setups the physical specific node variables.
  16186. *
  16187. * @param {NodeBuilder} builder - The current node builder.
  16188. */
  16189. setupVariants( builder ) {
  16190. super.setupVariants( builder );
  16191. // CLEARCOAT
  16192. if ( this.useClearcoat ) {
  16193. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  16194. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  16195. clearcoat.assign( clearcoatNode );
  16196. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  16197. }
  16198. // SHEEN
  16199. if ( this.useSheen ) {
  16200. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  16201. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  16202. sheen.assign( sheenNode );
  16203. sheenRoughness.assign( sheenRoughnessNode );
  16204. }
  16205. // IRIDESCENCE
  16206. if ( this.useIridescence ) {
  16207. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  16208. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  16209. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  16210. iridescence.assign( iridescenceNode );
  16211. iridescenceIOR.assign( iridescenceIORNode );
  16212. iridescenceThickness.assign( iridescenceThicknessNode );
  16213. }
  16214. // ANISOTROPY
  16215. if ( this.useAnisotropy ) {
  16216. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  16217. anisotropy.assign( anisotropyV.length() );
  16218. If( anisotropy.equal( 0.0 ), () => {
  16219. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  16220. } ).Else( () => {
  16221. anisotropyV.divAssign( vec2( anisotropy ) );
  16222. anisotropy.assign( anisotropy.saturate() );
  16223. } );
  16224. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  16225. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  16226. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  16227. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  16228. }
  16229. // TRANSMISSION
  16230. if ( this.useTransmission ) {
  16231. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  16232. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  16233. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  16234. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  16235. transmission.assign( transmissionNode );
  16236. thickness.assign( thicknessNode );
  16237. attenuationDistance.assign( attenuationDistanceNode );
  16238. attenuationColor.assign( attenuationColorNode );
  16239. if ( this.useDispersion ) {
  16240. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  16241. dispersion.assign( dispersionNode );
  16242. }
  16243. }
  16244. }
  16245. /**
  16246. * Setups the clearcoat normal node.
  16247. *
  16248. * @return {Node<vec3>} The clearcoat normal.
  16249. */
  16250. setupClearcoatNormal() {
  16251. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  16252. }
  16253. setup( builder ) {
  16254. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  16255. super.setup( builder );
  16256. }
  16257. copy( source ) {
  16258. this.clearcoatNode = source.clearcoatNode;
  16259. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  16260. this.clearcoatNormalNode = source.clearcoatNormalNode;
  16261. this.sheenNode = source.sheenNode;
  16262. this.sheenRoughnessNode = source.sheenRoughnessNode;
  16263. this.iridescenceNode = source.iridescenceNode;
  16264. this.iridescenceIORNode = source.iridescenceIORNode;
  16265. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  16266. this.specularIntensityNode = source.specularIntensityNode;
  16267. this.specularColorNode = source.specularColorNode;
  16268. this.transmissionNode = source.transmissionNode;
  16269. this.thicknessNode = source.thicknessNode;
  16270. this.attenuationDistanceNode = source.attenuationDistanceNode;
  16271. this.attenuationColorNode = source.attenuationColorNode;
  16272. this.dispersionNode = source.dispersionNode;
  16273. this.anisotropyNode = source.anisotropyNode;
  16274. return super.copy( source );
  16275. }
  16276. }
  16277. /**
  16278. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  16279. *
  16280. * @augments PhysicalLightingModel
  16281. */
  16282. class SSSLightingModel extends PhysicalLightingModel {
  16283. /**
  16284. * Constructs a new physical lighting model.
  16285. *
  16286. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16287. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16288. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16289. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16290. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16291. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16292. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  16293. */
  16294. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  16295. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  16296. /**
  16297. * Whether the lighting model should use SSS or not.
  16298. *
  16299. * @type {boolean}
  16300. * @default false
  16301. */
  16302. this.useSSS = sss;
  16303. }
  16304. /**
  16305. * Extends the default implementation with a SSS term.
  16306. *
  16307. * 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/}
  16308. *
  16309. * @param {Object} input - The input data.
  16310. * @param {NodeBuilder} builder - The current node builder.
  16311. */
  16312. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  16313. if ( this.useSSS === true ) {
  16314. const material = builder.material;
  16315. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  16316. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  16317. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  16318. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  16319. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  16320. }
  16321. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  16322. }
  16323. }
  16324. /**
  16325. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  16326. * that implements a Subsurface scattering (SSS) term.
  16327. *
  16328. * @augments MeshPhysicalNodeMaterial
  16329. */
  16330. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  16331. static get type() {
  16332. return 'MeshSSSNodeMaterial';
  16333. }
  16334. /**
  16335. * Constructs a new mesh SSS node material.
  16336. *
  16337. * @param {Object} [parameters] - The configuration parameter.
  16338. */
  16339. constructor( parameters ) {
  16340. super( parameters );
  16341. /**
  16342. * Represents the thickness color.
  16343. *
  16344. * @type {?Node<vec3>}
  16345. * @default null
  16346. */
  16347. this.thicknessColorNode = null;
  16348. /**
  16349. * Represents the distortion factor.
  16350. *
  16351. * @type {?Node<float>}
  16352. */
  16353. this.thicknessDistortionNode = float( 0.1 );
  16354. /**
  16355. * Represents the thickness ambient factor.
  16356. *
  16357. * @type {?Node<float>}
  16358. */
  16359. this.thicknessAmbientNode = float( 0.0 );
  16360. /**
  16361. * Represents the thickness attenuation.
  16362. *
  16363. * @type {?Node<float>}
  16364. */
  16365. this.thicknessAttenuationNode = float( .1 );
  16366. /**
  16367. * Represents the thickness power.
  16368. *
  16369. * @type {?Node<float>}
  16370. */
  16371. this.thicknessPowerNode = float( 2.0 );
  16372. /**
  16373. * Represents the thickness scale.
  16374. *
  16375. * @type {?Node<float>}
  16376. */
  16377. this.thicknessScaleNode = float( 10.0 );
  16378. }
  16379. /**
  16380. * Whether the lighting model should use SSS or not.
  16381. *
  16382. * @type {boolean}
  16383. * @default true
  16384. */
  16385. get useSSS() {
  16386. return this.thicknessColorNode !== null;
  16387. }
  16388. /**
  16389. * Setups the lighting model.
  16390. *
  16391. * @return {SSSLightingModel} The lighting model.
  16392. */
  16393. setupLightingModel( /*builder*/ ) {
  16394. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  16395. }
  16396. copy( source ) {
  16397. this.thicknessColorNode = source.thicknessColorNode;
  16398. this.thicknessDistortionNode = source.thicknessDistortionNode;
  16399. this.thicknessAmbientNode = source.thicknessAmbientNode;
  16400. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  16401. this.thicknessPowerNode = source.thicknessPowerNode;
  16402. this.thicknessScaleNode = source.thicknessScaleNode;
  16403. return super.copy( source );
  16404. }
  16405. }
  16406. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  16407. // dotNL will be from -1.0 to 1.0
  16408. const dotNL = normal.dot( lightDirection );
  16409. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  16410. if ( builder.material.gradientMap ) {
  16411. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  16412. return vec3( gradientMap.r );
  16413. } else {
  16414. const fw = coord.fwidth().mul( 0.5 );
  16415. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  16416. }
  16417. } );
  16418. /**
  16419. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  16420. *
  16421. * @augments LightingModel
  16422. */
  16423. class ToonLightingModel extends LightingModel {
  16424. /**
  16425. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  16426. * reduced to a small number of discrete shades to create a comic-like, flat look.
  16427. *
  16428. * @param {Object} lightData - The light data.
  16429. * @param {NodeBuilder} builder - The current node builder.
  16430. */
  16431. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  16432. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  16433. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16434. }
  16435. /**
  16436. * Implements the indirect lighting.
  16437. *
  16438. * @param {NodeBuilder} builder - The current node builder.
  16439. */
  16440. indirect( builder ) {
  16441. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  16442. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16443. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16444. }
  16445. }
  16446. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  16447. /**
  16448. * Node material version of {@link MeshToonMaterial}.
  16449. *
  16450. * @augments NodeMaterial
  16451. */
  16452. class MeshToonNodeMaterial extends NodeMaterial {
  16453. static get type() {
  16454. return 'MeshToonNodeMaterial';
  16455. }
  16456. /**
  16457. * Constructs a new mesh toon node material.
  16458. *
  16459. * @param {Object} [parameters] - The configuration parameter.
  16460. */
  16461. constructor( parameters ) {
  16462. super();
  16463. /**
  16464. * This flag can be used for type testing.
  16465. *
  16466. * @type {boolean}
  16467. * @readonly
  16468. * @default true
  16469. */
  16470. this.isMeshToonNodeMaterial = true;
  16471. /**
  16472. * Set to `true` because toon materials react on lights.
  16473. *
  16474. * @type {boolean}
  16475. * @default true
  16476. */
  16477. this.lights = true;
  16478. this.setDefaultValues( _defaultValues$4 );
  16479. this.setValues( parameters );
  16480. }
  16481. /**
  16482. * Setups the lighting model.
  16483. *
  16484. * @return {ToonLightingModel} The lighting model.
  16485. */
  16486. setupLightingModel( /*builder*/ ) {
  16487. return new ToonLightingModel();
  16488. }
  16489. }
  16490. /**
  16491. * Can be used to compute texture coordinates for projecting a
  16492. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  16493. *
  16494. * @augments TempNode
  16495. */
  16496. class MatcapUVNode extends TempNode {
  16497. static get type() {
  16498. return 'MatcapUVNode';
  16499. }
  16500. /**
  16501. * Constructs a new matcap uv node.
  16502. */
  16503. constructor() {
  16504. super( 'vec2' );
  16505. }
  16506. setup() {
  16507. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  16508. const y = positionViewDirection.cross( x );
  16509. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  16510. }
  16511. }
  16512. /**
  16513. * TSL function for creating a matcap uv node.
  16514. *
  16515. * @tsl
  16516. * @function
  16517. * @returns {MatcapUVNode}
  16518. */
  16519. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  16520. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  16521. /**
  16522. * Node material version of {@link MeshMatcapMaterial}.
  16523. *
  16524. * @augments NodeMaterial
  16525. */
  16526. class MeshMatcapNodeMaterial extends NodeMaterial {
  16527. static get type() {
  16528. return 'MeshMatcapNodeMaterial';
  16529. }
  16530. /**
  16531. * Constructs a new mesh normal node material.
  16532. *
  16533. * @param {Object} [parameters] - The configuration parameter.
  16534. */
  16535. constructor( parameters ) {
  16536. super();
  16537. /**
  16538. * This flag can be used for type testing.
  16539. *
  16540. * @type {boolean}
  16541. * @readonly
  16542. * @default true
  16543. */
  16544. this.isMeshMatcapNodeMaterial = true;
  16545. this.setDefaultValues( _defaultValues$3 );
  16546. this.setValues( parameters );
  16547. }
  16548. /**
  16549. * Setups the matcap specific node variables.
  16550. *
  16551. * @param {NodeBuilder} builder - The current node builder.
  16552. */
  16553. setupVariants( builder ) {
  16554. const uv = matcapUV;
  16555. let matcapColor;
  16556. if ( builder.material.matcap ) {
  16557. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  16558. } else {
  16559. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  16560. }
  16561. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  16562. }
  16563. }
  16564. /**
  16565. * Applies a rotation to the given position node.
  16566. *
  16567. * @augments TempNode
  16568. */
  16569. class RotateNode extends TempNode {
  16570. static get type() {
  16571. return 'RotateNode';
  16572. }
  16573. /**
  16574. * Constructs a new rotate node.
  16575. *
  16576. * @param {Node} positionNode - The position node.
  16577. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  16578. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  16579. */
  16580. constructor( positionNode, rotationNode ) {
  16581. super();
  16582. /**
  16583. * The position node.
  16584. *
  16585. * @type {Node}
  16586. */
  16587. this.positionNode = positionNode;
  16588. /**
  16589. * Represents the rotation that is applied to the position node.
  16590. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  16591. *
  16592. * @type {Node}
  16593. */
  16594. this.rotationNode = rotationNode;
  16595. }
  16596. /**
  16597. * The type of the {@link RotateNode#positionNode} defines the node's type.
  16598. *
  16599. * @param {NodeBuilder} builder - The current node builder.
  16600. * @return {string} The node's type.
  16601. */
  16602. getNodeType( builder ) {
  16603. return this.positionNode.getNodeType( builder );
  16604. }
  16605. setup( builder ) {
  16606. const { rotationNode, positionNode } = this;
  16607. const nodeType = this.getNodeType( builder );
  16608. if ( nodeType === 'vec2' ) {
  16609. const cosAngle = rotationNode.cos();
  16610. const sinAngle = rotationNode.sin();
  16611. const rotationMatrix = mat2(
  16612. cosAngle, sinAngle,
  16613. sinAngle.negate(), cosAngle
  16614. );
  16615. return rotationMatrix.mul( positionNode );
  16616. } else {
  16617. const rotation = rotationNode;
  16618. 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 ) );
  16619. 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 ) );
  16620. 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 ) );
  16621. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  16622. }
  16623. }
  16624. }
  16625. /**
  16626. * TSL function for creating a rotate node.
  16627. *
  16628. * @tsl
  16629. * @function
  16630. * @param {Node} positionNode - The position node.
  16631. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  16632. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  16633. * @returns {RotateNode}
  16634. */
  16635. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  16636. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  16637. /**
  16638. * Node material version of {@link SpriteMaterial}.
  16639. *
  16640. * @augments NodeMaterial
  16641. */
  16642. class SpriteNodeMaterial extends NodeMaterial {
  16643. static get type() {
  16644. return 'SpriteNodeMaterial';
  16645. }
  16646. /**
  16647. * Constructs a new sprite node material.
  16648. *
  16649. * @param {Object} [parameters] - The configuration parameter.
  16650. */
  16651. constructor( parameters ) {
  16652. super();
  16653. /**
  16654. * This flag can be used for type testing.
  16655. *
  16656. * @type {boolean}
  16657. * @readonly
  16658. * @default true
  16659. */
  16660. this.isSpriteNodeMaterial = true;
  16661. this._useSizeAttenuation = true;
  16662. /**
  16663. * This property makes it possible to define the position of the sprite with a
  16664. * node. That can be useful when the material is used with instanced rendering
  16665. * and node data are defined with an instanced attribute node:
  16666. * ```js
  16667. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  16668. * material.positionNode = instancedBufferAttribute( positionAttribute );
  16669. * ```
  16670. * Another possibility is to compute the instanced data with a compute shader:
  16671. * ```js
  16672. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  16673. * particleMaterial.positionNode = positionBuffer.toAttribute();
  16674. * ```
  16675. *
  16676. * @type {?Node<vec2>}
  16677. * @default null
  16678. */
  16679. this.positionNode = null;
  16680. /**
  16681. * The rotation of sprite materials is by default inferred from the `rotation`,
  16682. * property. This node property allows to overwrite the default and define
  16683. * the rotation with a node instead.
  16684. *
  16685. * If you don't want to overwrite the rotation but modify the existing
  16686. * value instead, use {@link materialRotation}.
  16687. *
  16688. * @type {?Node<float>}
  16689. * @default null
  16690. */
  16691. this.rotationNode = null;
  16692. /**
  16693. * This node property provides an additional way to scale sprites next to
  16694. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  16695. * is multiplied with the scale value of this node in the vertex shader.
  16696. *
  16697. * @type {?Node<vec2>}
  16698. * @default null
  16699. */
  16700. this.scaleNode = null;
  16701. /**
  16702. * In Sprites, the transparent property is enabled by default.
  16703. *
  16704. * @type {boolean}
  16705. * @default true
  16706. */
  16707. this.transparent = true;
  16708. this.setDefaultValues( _defaultValues$2 );
  16709. this.setValues( parameters );
  16710. }
  16711. /**
  16712. * Setups the position node in view space. This method implements
  16713. * the sprite specific vertex shader.
  16714. *
  16715. * @param {NodeBuilder} builder - The current node builder.
  16716. * @return {Node<vec3>} The position in view space.
  16717. */
  16718. setupPositionView( builder ) {
  16719. const { object, camera } = builder;
  16720. const sizeAttenuation = this.sizeAttenuation;
  16721. const { positionNode, rotationNode, scaleNode } = this;
  16722. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  16723. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  16724. if ( scaleNode !== null ) {
  16725. scale = scale.mul( vec2( scaleNode ) );
  16726. }
  16727. if ( sizeAttenuation === false ) {
  16728. if ( camera.isPerspectiveCamera ) {
  16729. scale = scale.mul( mvPosition.z.negate() );
  16730. } else {
  16731. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  16732. scale = scale.mul( orthoScale.mul( 2 ) );
  16733. }
  16734. }
  16735. let alignedPosition = positionGeometry.xy;
  16736. if ( object.center && object.center.isVector2 === true ) {
  16737. const center = reference$1( 'center', 'vec2', object );
  16738. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  16739. }
  16740. alignedPosition = alignedPosition.mul( scale );
  16741. const rotation = float( rotationNode || materialRotation );
  16742. const rotatedPosition = rotate( alignedPosition, rotation );
  16743. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  16744. }
  16745. copy( source ) {
  16746. this.positionNode = source.positionNode;
  16747. this.rotationNode = source.rotationNode;
  16748. this.scaleNode = source.scaleNode;
  16749. return super.copy( source );
  16750. }
  16751. /**
  16752. * Whether to use size attenuation or not.
  16753. *
  16754. * @type {boolean}
  16755. * @default true
  16756. */
  16757. get sizeAttenuation() {
  16758. return this._useSizeAttenuation;
  16759. }
  16760. set sizeAttenuation( value ) {
  16761. if ( this._useSizeAttenuation !== value ) {
  16762. this._useSizeAttenuation = value;
  16763. this.needsUpdate = true;
  16764. }
  16765. }
  16766. }
  16767. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  16768. /**
  16769. * Node material version of {@link PointsMaterial}.
  16770. *
  16771. * @augments SpriteNodeMaterial
  16772. */
  16773. class PointsNodeMaterial extends SpriteNodeMaterial {
  16774. static get type() {
  16775. return 'PointsNodeMaterial';
  16776. }
  16777. /**
  16778. * Constructs a new points node material.
  16779. *
  16780. * @param {Object} [parameters] - The configuration parameter.
  16781. */
  16782. constructor( parameters ) {
  16783. super();
  16784. /**
  16785. * This node property provides an additional way to set the point size.
  16786. *
  16787. * @type {?Node<vec2>}
  16788. * @default null
  16789. */
  16790. this.sizeNode = null;
  16791. /**
  16792. * This flag can be used for type testing.
  16793. *
  16794. * @type {boolean}
  16795. * @readonly
  16796. * @default true
  16797. */
  16798. this.isPointsNodeMaterial = true;
  16799. this.setDefaultValues( _defaultValues$1 );
  16800. this.setValues( parameters );
  16801. }
  16802. setupPositionView() {
  16803. const { positionNode } = this;
  16804. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  16805. }
  16806. setupVertex( builder ) {
  16807. const mvp = super.setupVertex( builder );
  16808. // skip further processing if the material is not a node material
  16809. if ( builder.material.isNodeMaterial !== true ) {
  16810. return mvp;
  16811. }
  16812. // ndc space
  16813. const { rotationNode, scaleNode, sizeNode } = this;
  16814. const alignedPosition = positionGeometry.xy.toVar();
  16815. const aspect = viewport.z.div( viewport.w );
  16816. // rotation
  16817. if ( rotationNode && rotationNode.isNode ) {
  16818. const rotation = float( rotationNode );
  16819. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  16820. }
  16821. // point size
  16822. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  16823. if ( this.sizeAttenuation === true ) {
  16824. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  16825. }
  16826. // scale
  16827. if ( scaleNode && scaleNode.isNode ) {
  16828. pointSize = pointSize.mul( vec2( scaleNode ) );
  16829. }
  16830. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  16831. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  16832. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  16833. // back to clip space
  16834. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  16835. //clipPos.xy += offset;
  16836. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  16837. return mvp;
  16838. }
  16839. /**
  16840. * Whether alpha to coverage should be used or not.
  16841. *
  16842. * @type {boolean}
  16843. * @default true
  16844. */
  16845. get alphaToCoverage() {
  16846. return this._useAlphaToCoverage;
  16847. }
  16848. set alphaToCoverage( value ) {
  16849. if ( this._useAlphaToCoverage !== value ) {
  16850. this._useAlphaToCoverage = value;
  16851. this.needsUpdate = true;
  16852. }
  16853. }
  16854. }
  16855. /**
  16856. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  16857. *
  16858. * @augments LightingModel
  16859. */
  16860. class ShadowMaskModel extends LightingModel {
  16861. /**
  16862. * Constructs a new shadow mask model.
  16863. */
  16864. constructor() {
  16865. super();
  16866. /**
  16867. * The shadow mask node.
  16868. *
  16869. * @type {Node}
  16870. */
  16871. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  16872. }
  16873. /**
  16874. * Only used to save the shadow mask.
  16875. *
  16876. * @param {Object} input - The input data.
  16877. */
  16878. direct( { shadowMask } ) {
  16879. this.shadowNode.mulAssign( shadowMask );
  16880. }
  16881. /**
  16882. * Uses the shadow mask to produce the final color.
  16883. *
  16884. * @param {ContextNode} context - The current node context.
  16885. */
  16886. finish( context ) {
  16887. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  16888. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  16889. }
  16890. }
  16891. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  16892. /**
  16893. * Node material version of {@link ShadowMaterial}.
  16894. *
  16895. * @augments NodeMaterial
  16896. */
  16897. class ShadowNodeMaterial extends NodeMaterial {
  16898. static get type() {
  16899. return 'ShadowNodeMaterial';
  16900. }
  16901. /**
  16902. * Constructs a new shadow node material.
  16903. *
  16904. * @param {Object} [parameters] - The configuration parameter.
  16905. */
  16906. constructor( parameters ) {
  16907. super();
  16908. /**
  16909. * This flag can be used for type testing.
  16910. *
  16911. * @type {boolean}
  16912. * @readonly
  16913. * @default true
  16914. */
  16915. this.isShadowNodeMaterial = true;
  16916. /**
  16917. * Set to `true` because so it's possible to implement
  16918. * the shadow mask effect.
  16919. *
  16920. * @type {boolean}
  16921. * @default true
  16922. */
  16923. this.lights = true;
  16924. this.setDefaultValues( _defaultValues );
  16925. this.setValues( parameters );
  16926. }
  16927. /**
  16928. * Setups the lighting model.
  16929. *
  16930. * @return {ShadowMaskModel} The lighting model.
  16931. */
  16932. setupLightingModel( /*builder*/ ) {
  16933. return new ShadowMaskModel();
  16934. }
  16935. }
  16936. const scatteringDensity = property( 'vec3' );
  16937. const linearDepthRay = property( 'vec3' );
  16938. const outgoingRayLight = property( 'vec3' );
  16939. /**
  16940. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  16941. * This model calculates the scattering and transmittance of light through a volumetric medium.
  16942. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  16943. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  16944. *
  16945. * @augments LightingModel
  16946. */
  16947. class VolumetricLightingModel extends LightingModel {
  16948. constructor() {
  16949. super();
  16950. }
  16951. start( builder ) {
  16952. const { material, context } = builder;
  16953. const startPos = property( 'vec3' );
  16954. const endPos = property( 'vec3' );
  16955. // This approach dynamically changes the direction of the ray,
  16956. // prioritizing the ray from the camera to the object if it is inside the mesh, and from the object to the camera if it is far away.
  16957. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  16958. startPos.assign( cameraPosition );
  16959. endPos.assign( positionWorld );
  16960. } ).Else( () => {
  16961. startPos.assign( positionWorld );
  16962. endPos.assign( cameraPosition );
  16963. } );
  16964. //
  16965. const viewVector = endPos.sub( startPos );
  16966. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  16967. const stepSize = viewVector.length().div( steps ).toVar();
  16968. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  16969. const distTravelled = float( 0.0 ).toVar();
  16970. const transmittance = vec3( 1 ).toVar();
  16971. if ( material.offsetNode ) {
  16972. // reduce banding
  16973. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  16974. }
  16975. Loop( steps, () => {
  16976. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  16977. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  16978. if ( material.depthNode !== null ) {
  16979. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  16980. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  16981. }
  16982. context.positionWorld = positionRay;
  16983. context.shadowPositionWorld = positionRay;
  16984. context.positionView = positionViewRay;
  16985. scatteringDensity.assign( 0 );
  16986. let scatteringNode;
  16987. if ( material.scatteringNode ) {
  16988. scatteringNode = material.scatteringNode( {
  16989. positionRay
  16990. } );
  16991. }
  16992. super.start( builder );
  16993. if ( scatteringNode ) {
  16994. scatteringDensity.mulAssign( scatteringNode );
  16995. }
  16996. // beer's law
  16997. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  16998. transmittance.mulAssign( falloff );
  16999. // move along the ray
  17000. distTravelled.addAssign( stepSize );
  17001. } );
  17002. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  17003. }
  17004. scatteringLight( lightColor, builder ) {
  17005. const sceneDepthNode = builder.context.sceneDepthNode;
  17006. if ( sceneDepthNode ) {
  17007. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  17008. scatteringDensity.addAssign( lightColor );
  17009. } );
  17010. } else {
  17011. scatteringDensity.addAssign( lightColor );
  17012. }
  17013. }
  17014. direct( { lightNode, lightColor }, builder ) {
  17015. // Ignore lights with infinite distance
  17016. if ( lightNode.light.distance === undefined ) return;
  17017. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  17018. const directLight = lightColor.xyz.toVar();
  17019. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  17020. this.scatteringLight( directLight, builder );
  17021. }
  17022. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  17023. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17024. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17025. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17026. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17027. const P = builder.context.positionView;
  17028. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  17029. this.scatteringLight( directLight, builder );
  17030. }
  17031. finish( builder ) {
  17032. builder.context.outgoingLight.assign( outgoingRayLight );
  17033. }
  17034. }
  17035. /**
  17036. * Volume node material.
  17037. *
  17038. * @augments NodeMaterial
  17039. */
  17040. class VolumeNodeMaterial extends NodeMaterial {
  17041. static get type() {
  17042. return 'VolumeNodeMaterial';
  17043. }
  17044. /**
  17045. * Constructs a new volume node material.
  17046. *
  17047. * @param {Object} [parameters] - The configuration parameter.
  17048. */
  17049. constructor( parameters ) {
  17050. super();
  17051. /**
  17052. * This flag can be used for type testing.
  17053. *
  17054. * @type {boolean}
  17055. * @readonly
  17056. * @default true
  17057. */
  17058. this.isVolumeNodeMaterial = true;
  17059. /**
  17060. * Number of steps used for raymarching.
  17061. *
  17062. * @type {number}
  17063. * @default 25
  17064. */
  17065. this.steps = 25;
  17066. /**
  17067. * Offsets the distance a ray has been traveled through a volume.
  17068. * Can be used to implement dithering to reduce banding.
  17069. *
  17070. * @type {Node<float>}
  17071. * @default null
  17072. */
  17073. this.offsetNode = null;
  17074. /**
  17075. * Node used for scattering calculations.
  17076. *
  17077. * @type {Function|FunctionNode<vec4>}
  17078. * @default null
  17079. */
  17080. this.scatteringNode = null;
  17081. this.lights = true;
  17082. this.transparent = true;
  17083. this.side = BackSide;
  17084. this.depthTest = false;
  17085. this.depthWrite = false;
  17086. this.setValues( parameters );
  17087. }
  17088. setupLightingModel() {
  17089. return new VolumetricLightingModel();
  17090. }
  17091. }
  17092. /**
  17093. * This module manages the internal animation loop of the renderer.
  17094. *
  17095. * @private
  17096. */
  17097. class Animation {
  17098. /**
  17099. * Constructs a new animation loop management component.
  17100. *
  17101. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17102. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17103. */
  17104. constructor( nodes, info ) {
  17105. /**
  17106. * Renderer component for managing nodes related logic.
  17107. *
  17108. * @type {Nodes}
  17109. */
  17110. this.nodes = nodes;
  17111. /**
  17112. * Renderer component for managing metrics and monitoring data.
  17113. *
  17114. * @type {Info}
  17115. */
  17116. this.info = info;
  17117. /**
  17118. * A reference to the context from `requestAnimationFrame()` can
  17119. * be called (usually `window`).
  17120. *
  17121. * @type {Window|XRSession}
  17122. */
  17123. this._context = self;
  17124. /**
  17125. * The user-defined animation loop.
  17126. *
  17127. * @type {?Function}
  17128. * @default null
  17129. */
  17130. this._animationLoop = null;
  17131. /**
  17132. * The requestId which is returned from the `requestAnimationFrame()` call.
  17133. * Can be used to cancel the stop the animation loop.
  17134. *
  17135. * @type {?number}
  17136. * @default null
  17137. */
  17138. this._requestId = null;
  17139. }
  17140. /**
  17141. * Starts the internal animation loop.
  17142. */
  17143. start() {
  17144. const update = ( time, xrFrame ) => {
  17145. this._requestId = this._context.requestAnimationFrame( update );
  17146. if ( this.info.autoReset === true ) this.info.reset();
  17147. this.nodes.nodeFrame.update();
  17148. this.info.frame = this.nodes.nodeFrame.frameId;
  17149. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  17150. };
  17151. update();
  17152. }
  17153. /**
  17154. * Stops the internal animation loop.
  17155. */
  17156. stop() {
  17157. this._context.cancelAnimationFrame( this._requestId );
  17158. this._requestId = null;
  17159. }
  17160. /**
  17161. * Returns the user-level animation loop.
  17162. *
  17163. * @return {?Function} The animation loop.
  17164. */
  17165. getAnimationLoop() {
  17166. return this._animationLoop;
  17167. }
  17168. /**
  17169. * Defines the user-level animation loop.
  17170. *
  17171. * @param {?Function} callback - The animation loop.
  17172. */
  17173. setAnimationLoop( callback ) {
  17174. this._animationLoop = callback;
  17175. }
  17176. /**
  17177. * Returns the animation context.
  17178. *
  17179. * @return {Window|XRSession} The animation context.
  17180. */
  17181. getContext() {
  17182. return this._context;
  17183. }
  17184. /**
  17185. * Defines the context in which `requestAnimationFrame()` is executed.
  17186. *
  17187. * @param {Window|XRSession} context - The context to set.
  17188. */
  17189. setContext( context ) {
  17190. this._context = context;
  17191. }
  17192. /**
  17193. * Frees all internal resources and stops the animation loop.
  17194. */
  17195. dispose() {
  17196. this.stop();
  17197. }
  17198. }
  17199. /**
  17200. * Data structure for the renderer. It allows defining values
  17201. * with chained, hierarchical keys. Keys are meant to be
  17202. * objects since the module internally works with Weak Maps
  17203. * for performance reasons.
  17204. *
  17205. * @private
  17206. */
  17207. class ChainMap {
  17208. /**
  17209. * Constructs a new Chain Map.
  17210. */
  17211. constructor() {
  17212. /**
  17213. * The root Weak Map.
  17214. *
  17215. * @type {WeakMap}
  17216. */
  17217. this.weakMap = new WeakMap();
  17218. }
  17219. /**
  17220. * Returns the value for the given array of keys.
  17221. *
  17222. * @param {Array<Object>} keys - List of keys.
  17223. * @return {any} The value. Returns `undefined` if no value was found.
  17224. */
  17225. get( keys ) {
  17226. let map = this.weakMap;
  17227. for ( let i = 0; i < keys.length - 1; i ++ ) {
  17228. map = map.get( keys[ i ] );
  17229. if ( map === undefined ) return undefined;
  17230. }
  17231. return map.get( keys[ keys.length - 1 ] );
  17232. }
  17233. /**
  17234. * Sets the value for the given keys.
  17235. *
  17236. * @param {Array<Object>} keys - List of keys.
  17237. * @param {any} value - The value to set.
  17238. * @return {ChainMap} A reference to this Chain Map.
  17239. */
  17240. set( keys, value ) {
  17241. let map = this.weakMap;
  17242. for ( let i = 0; i < keys.length - 1; i ++ ) {
  17243. const key = keys[ i ];
  17244. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  17245. map = map.get( key );
  17246. }
  17247. map.set( keys[ keys.length - 1 ], value );
  17248. return this;
  17249. }
  17250. /**
  17251. * Deletes a value for the given keys.
  17252. *
  17253. * @param {Array<Object>} keys - The keys.
  17254. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  17255. */
  17256. delete( keys ) {
  17257. let map = this.weakMap;
  17258. for ( let i = 0; i < keys.length - 1; i ++ ) {
  17259. map = map.get( keys[ i ] );
  17260. if ( map === undefined ) return false;
  17261. }
  17262. return map.delete( keys[ keys.length - 1 ] );
  17263. }
  17264. }
  17265. let _id$9 = 0;
  17266. function getKeys( obj ) {
  17267. const keys = Object.keys( obj );
  17268. let proto = Object.getPrototypeOf( obj );
  17269. while ( proto ) {
  17270. const descriptors = Object.getOwnPropertyDescriptors( proto );
  17271. for ( const key in descriptors ) {
  17272. if ( descriptors[ key ] !== undefined ) {
  17273. const descriptor = descriptors[ key ];
  17274. if ( descriptor && typeof descriptor.get === 'function' ) {
  17275. keys.push( key );
  17276. }
  17277. }
  17278. }
  17279. proto = Object.getPrototypeOf( proto );
  17280. }
  17281. return keys;
  17282. }
  17283. /**
  17284. * A render object is the renderer's representation of single entity that gets drawn
  17285. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  17286. * scene since render objects also depend from the used material, the current render context
  17287. * and the current scene's lighting.
  17288. *
  17289. * In general, the basic process of the renderer is:
  17290. *
  17291. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  17292. * - Process the render lists by calling one or more render commands for each render item.
  17293. * - For each render command, request a render object and perform the draw.
  17294. *
  17295. * The module provides an interface to get data required for the draw command like the actual
  17296. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  17297. * creating render objects should only be done when necessary.
  17298. *
  17299. * @private
  17300. */
  17301. class RenderObject {
  17302. /**
  17303. * Constructs a new render object.
  17304. *
  17305. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17306. * @param {Geometries} geometries - Renderer component for managing geometries.
  17307. * @param {Renderer} renderer - The renderer.
  17308. * @param {Object3D} object - The 3D object.
  17309. * @param {Material} material - The 3D object's material.
  17310. * @param {Scene} scene - The scene the 3D object belongs to.
  17311. * @param {Camera} camera - The camera the object should be rendered with.
  17312. * @param {LightsNode} lightsNode - The lights node.
  17313. * @param {RenderContext} renderContext - The render context.
  17314. * @param {ClippingContext} clippingContext - The clipping context.
  17315. */
  17316. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  17317. this.id = _id$9 ++;
  17318. /**
  17319. * Renderer component for managing nodes related logic.
  17320. *
  17321. * @type {Nodes}
  17322. * @private
  17323. */
  17324. this._nodes = nodes;
  17325. /**
  17326. * Renderer component for managing geometries.
  17327. *
  17328. * @type {Geometries}
  17329. * @private
  17330. */
  17331. this._geometries = geometries;
  17332. /**
  17333. * The renderer.
  17334. *
  17335. * @type {Renderer}
  17336. */
  17337. this.renderer = renderer;
  17338. /**
  17339. * The 3D object.
  17340. *
  17341. * @type {Object3D}
  17342. */
  17343. this.object = object;
  17344. /**
  17345. * The 3D object's material.
  17346. *
  17347. * @type {Material}
  17348. */
  17349. this.material = material;
  17350. /**
  17351. * The scene the 3D object belongs to.
  17352. *
  17353. * @type {Scene}
  17354. */
  17355. this.scene = scene;
  17356. /**
  17357. * The camera the 3D object should be rendered with.
  17358. *
  17359. * @type {Camera}
  17360. */
  17361. this.camera = camera;
  17362. /**
  17363. * The lights node.
  17364. *
  17365. * @type {LightsNode}
  17366. */
  17367. this.lightsNode = lightsNode;
  17368. /**
  17369. * The render context.
  17370. *
  17371. * @type {RenderContext}
  17372. */
  17373. this.context = renderContext;
  17374. /**
  17375. * The 3D object's geometry.
  17376. *
  17377. * @type {BufferGeometry}
  17378. */
  17379. this.geometry = object.geometry;
  17380. /**
  17381. * The render object's version.
  17382. *
  17383. * @type {number}
  17384. */
  17385. this.version = material.version;
  17386. /**
  17387. * The draw range of the geometry.
  17388. *
  17389. * @type {?Object}
  17390. * @default null
  17391. */
  17392. this.drawRange = null;
  17393. /**
  17394. * An array holding the buffer attributes
  17395. * of the render object. This entails attribute
  17396. * definitions on geometry and node level.
  17397. *
  17398. * @type {?Array<BufferAttribute>}
  17399. * @default null
  17400. */
  17401. this.attributes = null;
  17402. /**
  17403. * A reference to a render pipeline the render
  17404. * object is processed with.
  17405. *
  17406. * @type {RenderPipeline}
  17407. * @default null
  17408. */
  17409. this.pipeline = null;
  17410. /**
  17411. * Only relevant for objects using
  17412. * multiple materials. This represents a group entry
  17413. * from the respective `BufferGeometry`.
  17414. *
  17415. * @type {?{start: number, count: number}}
  17416. * @default null
  17417. */
  17418. this.group = null;
  17419. /**
  17420. * An array holding the vertex buffers which can
  17421. * be buffer attributes but also interleaved buffers.
  17422. *
  17423. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  17424. * @default null
  17425. */
  17426. this.vertexBuffers = null;
  17427. /**
  17428. * The parameters for the draw command.
  17429. *
  17430. * @type {?Object}
  17431. * @default null
  17432. */
  17433. this.drawParams = null;
  17434. /**
  17435. * If this render object is used inside a render bundle,
  17436. * this property points to the respective bundle group.
  17437. *
  17438. * @type {?BundleGroup}
  17439. * @default null
  17440. */
  17441. this.bundle = null;
  17442. /**
  17443. * The clipping context.
  17444. *
  17445. * @type {ClippingContext}
  17446. */
  17447. this.clippingContext = clippingContext;
  17448. /**
  17449. * The clipping context's cache key.
  17450. *
  17451. * @type {string}
  17452. */
  17453. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  17454. /**
  17455. * The initial node cache key.
  17456. *
  17457. * @type {number}
  17458. */
  17459. this.initialNodesCacheKey = this.getDynamicCacheKey();
  17460. /**
  17461. * The initial cache key.
  17462. *
  17463. * @type {number}
  17464. */
  17465. this.initialCacheKey = this.getCacheKey();
  17466. /**
  17467. * The node builder state.
  17468. *
  17469. * @type {?NodeBuilderState}
  17470. * @private
  17471. * @default null
  17472. */
  17473. this._nodeBuilderState = null;
  17474. /**
  17475. * An array of bindings.
  17476. *
  17477. * @type {?Array<BindGroup>}
  17478. * @private
  17479. * @default null
  17480. */
  17481. this._bindings = null;
  17482. /**
  17483. * Reference to the node material observer.
  17484. *
  17485. * @type {?NodeMaterialObserver}
  17486. * @private
  17487. * @default null
  17488. */
  17489. this._monitor = null;
  17490. /**
  17491. * An event listener which is defined by `RenderObjects`. It performs
  17492. * clean up tasks when `dispose()` on this render object.
  17493. *
  17494. * @method
  17495. */
  17496. this.onDispose = null;
  17497. /**
  17498. * This flag can be used for type testing.
  17499. *
  17500. * @type {boolean}
  17501. * @readonly
  17502. * @default true
  17503. */
  17504. this.isRenderObject = true;
  17505. /**
  17506. * An event listener which is executed when `dispose()` is called on
  17507. * the render object's material.
  17508. *
  17509. * @method
  17510. */
  17511. this.onMaterialDispose = () => {
  17512. this.dispose();
  17513. };
  17514. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  17515. }
  17516. /**
  17517. * Updates the clipping context.
  17518. *
  17519. * @param {ClippingContext} context - The clipping context to set.
  17520. */
  17521. updateClipping( context ) {
  17522. this.clippingContext = context;
  17523. }
  17524. /**
  17525. * Whether the clipping requires an update or not.
  17526. *
  17527. * @type {boolean}
  17528. * @readonly
  17529. */
  17530. get clippingNeedsUpdate() {
  17531. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  17532. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  17533. return true;
  17534. }
  17535. /**
  17536. * The number of clipping planes defined in context of hardware clipping.
  17537. *
  17538. * @type {number}
  17539. * @readonly
  17540. */
  17541. get hardwareClippingPlanes() {
  17542. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  17543. }
  17544. /**
  17545. * Returns the node builder state of this render object.
  17546. *
  17547. * @return {NodeBuilderState} The node builder state.
  17548. */
  17549. getNodeBuilderState() {
  17550. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  17551. }
  17552. /**
  17553. * Returns the node material observer of this render object.
  17554. *
  17555. * @return {NodeMaterialObserver} The node material observer.
  17556. */
  17557. getMonitor() {
  17558. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  17559. }
  17560. /**
  17561. * Returns an array of bind groups of this render object.
  17562. *
  17563. * @return {Array<BindGroup>} The bindings.
  17564. */
  17565. getBindings() {
  17566. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  17567. }
  17568. /**
  17569. * Returns a binding group by group name of this render object.
  17570. *
  17571. * @param {string} name - The name of the binding group.
  17572. * @return {?BindGroup} The bindings.
  17573. */
  17574. getBindingGroup( name ) {
  17575. for ( const bindingGroup of this.getBindings() ) {
  17576. if ( bindingGroup.name === name ) {
  17577. return bindingGroup;
  17578. }
  17579. }
  17580. }
  17581. /**
  17582. * Returns the index of the render object's geometry.
  17583. *
  17584. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  17585. */
  17586. getIndex() {
  17587. return this._geometries.getIndex( this );
  17588. }
  17589. /**
  17590. * Returns the indirect buffer attribute.
  17591. *
  17592. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  17593. */
  17594. getIndirect() {
  17595. return this._geometries.getIndirect( this );
  17596. }
  17597. /**
  17598. * Returns an array that acts as a key for identifying the render object in a chain map.
  17599. *
  17600. * @return {Array<Object>} An array with object references.
  17601. */
  17602. getChainArray() {
  17603. return [ this.object, this.material, this.context, this.lightsNode ];
  17604. }
  17605. /**
  17606. * This method is used when the geometry of a 3D object has been exchanged and the
  17607. * respective render object now requires an update.
  17608. *
  17609. * @param {BufferGeometry} geometry - The geometry to set.
  17610. */
  17611. setGeometry( geometry ) {
  17612. this.geometry = geometry;
  17613. this.attributes = null;
  17614. }
  17615. /**
  17616. * Returns the buffer attributes of the render object. The returned array holds
  17617. * attribute definitions on geometry and node level.
  17618. *
  17619. * @return {Array<BufferAttribute>} An array with buffer attributes.
  17620. */
  17621. getAttributes() {
  17622. if ( this.attributes !== null ) return this.attributes;
  17623. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  17624. const geometry = this.geometry;
  17625. const attributes = [];
  17626. const vertexBuffers = new Set();
  17627. for ( const nodeAttribute of nodeAttributes ) {
  17628. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  17629. if ( attribute === undefined ) continue;
  17630. attributes.push( attribute );
  17631. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  17632. vertexBuffers.add( bufferAttribute );
  17633. }
  17634. this.attributes = attributes;
  17635. this.vertexBuffers = Array.from( vertexBuffers.values() );
  17636. return attributes;
  17637. }
  17638. /**
  17639. * Returns the vertex buffers of the render object.
  17640. *
  17641. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  17642. */
  17643. getVertexBuffers() {
  17644. if ( this.vertexBuffers === null ) this.getAttributes();
  17645. return this.vertexBuffers;
  17646. }
  17647. /**
  17648. * Returns the draw parameters for the render object.
  17649. *
  17650. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  17651. */
  17652. getDrawParameters() {
  17653. const { object, material, geometry, group, drawRange } = this;
  17654. const drawParams = this.drawParams || ( this.drawParams = {
  17655. vertexCount: 0,
  17656. firstVertex: 0,
  17657. instanceCount: 0,
  17658. firstInstance: 0
  17659. } );
  17660. const index = this.getIndex();
  17661. const hasIndex = ( index !== null );
  17662. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  17663. if ( instanceCount === 0 ) return null;
  17664. drawParams.instanceCount = instanceCount;
  17665. if ( object.isBatchedMesh === true ) return drawParams;
  17666. let rangeFactor = 1;
  17667. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  17668. rangeFactor = 2;
  17669. }
  17670. let firstVertex = drawRange.start * rangeFactor;
  17671. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  17672. if ( group !== null ) {
  17673. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  17674. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  17675. }
  17676. const position = geometry.attributes.position;
  17677. let itemCount = Infinity;
  17678. if ( hasIndex ) {
  17679. itemCount = index.count;
  17680. } else if ( position !== undefined && position !== null ) {
  17681. itemCount = position.count;
  17682. }
  17683. firstVertex = Math.max( firstVertex, 0 );
  17684. lastVertex = Math.min( lastVertex, itemCount );
  17685. const count = lastVertex - firstVertex;
  17686. if ( count < 0 || count === Infinity ) return null;
  17687. drawParams.vertexCount = count;
  17688. drawParams.firstVertex = firstVertex;
  17689. return drawParams;
  17690. }
  17691. /**
  17692. * Returns the render object's geometry cache key.
  17693. *
  17694. * The geometry cache key is part of the material cache key.
  17695. *
  17696. * @return {string} The geometry cache key.
  17697. */
  17698. getGeometryCacheKey() {
  17699. const { geometry } = this;
  17700. let cacheKey = '';
  17701. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  17702. const attribute = geometry.attributes[ name ];
  17703. cacheKey += name + ',';
  17704. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  17705. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  17706. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  17707. if ( attribute.normalized ) cacheKey += 'n,';
  17708. }
  17709. // structural equality isn't sufficient for morph targets since the
  17710. // data are maintained in textures. only if the targets are all equal
  17711. // the texture and thus the instance of `MorphNode` can be shared.
  17712. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  17713. const targets = geometry.morphAttributes[ name ];
  17714. cacheKey += 'morph-' + name + ',';
  17715. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  17716. const attribute = targets[ i ];
  17717. cacheKey += attribute.id + ',';
  17718. }
  17719. }
  17720. if ( geometry.index ) {
  17721. cacheKey += 'index,';
  17722. }
  17723. return cacheKey;
  17724. }
  17725. /**
  17726. * Returns the render object's material cache key.
  17727. *
  17728. * The material cache key is part of the render object cache key.
  17729. *
  17730. * @return {number} The material cache key.
  17731. */
  17732. getMaterialCacheKey() {
  17733. const { object, material } = this;
  17734. let cacheKey = material.customProgramCacheKey();
  17735. for ( const property of getKeys( material ) ) {
  17736. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  17737. const value = material[ property ];
  17738. let valueKey;
  17739. if ( value !== null ) {
  17740. // some material values require a formatting
  17741. const type = typeof value;
  17742. if ( type === 'number' ) {
  17743. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  17744. } else if ( type === 'object' ) {
  17745. valueKey = '{';
  17746. if ( value.isTexture ) {
  17747. valueKey += value.mapping;
  17748. }
  17749. valueKey += '}';
  17750. } else {
  17751. valueKey = String( value );
  17752. }
  17753. } else {
  17754. valueKey = String( value );
  17755. }
  17756. cacheKey += /*property + ':' +*/ valueKey + ',';
  17757. }
  17758. cacheKey += this.clippingContextCacheKey + ',';
  17759. if ( object.geometry ) {
  17760. cacheKey += this.getGeometryCacheKey();
  17761. }
  17762. if ( object.skeleton ) {
  17763. cacheKey += object.skeleton.bones.length + ',';
  17764. }
  17765. if ( object.isBatchedMesh ) {
  17766. cacheKey += object._matricesTexture.uuid + ',';
  17767. if ( object._colorsTexture !== null ) {
  17768. cacheKey += object._colorsTexture.uuid + ',';
  17769. }
  17770. }
  17771. if ( object.count > 1 ) {
  17772. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  17773. cacheKey += object.uuid + ',';
  17774. }
  17775. cacheKey += object.receiveShadow + ',';
  17776. return hashString( cacheKey );
  17777. }
  17778. /**
  17779. * Whether the geometry requires an update or not.
  17780. *
  17781. * @type {boolean}
  17782. * @readonly
  17783. */
  17784. get needsGeometryUpdate() {
  17785. return this.geometry.id !== this.object.geometry.id;
  17786. }
  17787. /**
  17788. * Whether the render object requires an update or not.
  17789. *
  17790. * Note: There are two distinct places where render objects are checked for an update.
  17791. *
  17792. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  17793. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  17794. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  17795. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  17796. * a need for a refresh due to material, geometry or object related value changes.
  17797. *
  17798. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  17799. * that performs the 'needsUpdate' check.
  17800. *
  17801. * @type {boolean}
  17802. * @readonly
  17803. */
  17804. get needsUpdate() {
  17805. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  17806. }
  17807. /**
  17808. * Returns the dynamic cache key which represents a key that is computed per draw command.
  17809. *
  17810. * @return {number} The cache key.
  17811. */
  17812. getDynamicCacheKey() {
  17813. let cacheKey = 0;
  17814. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  17815. // the renderer is inside a shadow pass.
  17816. if ( this.material.isShadowPassMaterial !== true ) {
  17817. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  17818. }
  17819. if ( this.camera.isArrayCamera ) {
  17820. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  17821. }
  17822. if ( this.object.receiveShadow ) {
  17823. cacheKey = hash$1( cacheKey, 1 );
  17824. }
  17825. return cacheKey;
  17826. }
  17827. /**
  17828. * Returns the render object's cache key.
  17829. *
  17830. * @return {number} The cache key.
  17831. */
  17832. getCacheKey() {
  17833. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  17834. }
  17835. /**
  17836. * Frees internal resources.
  17837. */
  17838. dispose() {
  17839. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  17840. this.onDispose();
  17841. }
  17842. }
  17843. const _chainKeys$5 = [];
  17844. /**
  17845. * This module manages the render objects of the renderer.
  17846. *
  17847. * @private
  17848. */
  17849. class RenderObjects {
  17850. /**
  17851. * Constructs a new render object management component.
  17852. *
  17853. * @param {Renderer} renderer - The renderer.
  17854. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17855. * @param {Geometries} geometries - Renderer component for managing geometries.
  17856. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17857. * @param {Bindings} bindings - Renderer component for managing bindings.
  17858. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17859. */
  17860. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  17861. /**
  17862. * The renderer.
  17863. *
  17864. * @type {Renderer}
  17865. */
  17866. this.renderer = renderer;
  17867. /**
  17868. * Renderer component for managing nodes related logic.
  17869. *
  17870. * @type {Nodes}
  17871. */
  17872. this.nodes = nodes;
  17873. /**
  17874. * Renderer component for managing geometries.
  17875. *
  17876. * @type {Geometries}
  17877. */
  17878. this.geometries = geometries;
  17879. /**
  17880. * Renderer component for managing pipelines.
  17881. *
  17882. * @type {Pipelines}
  17883. */
  17884. this.pipelines = pipelines;
  17885. /**
  17886. * Renderer component for managing bindings.
  17887. *
  17888. * @type {Bindings}
  17889. */
  17890. this.bindings = bindings;
  17891. /**
  17892. * Renderer component for managing metrics and monitoring data.
  17893. *
  17894. * @type {Info}
  17895. */
  17896. this.info = info;
  17897. /**
  17898. * A dictionary that manages render contexts in chain maps
  17899. * for each pass ID.
  17900. *
  17901. * @type {Object<string,ChainMap>}
  17902. */
  17903. this.chainMaps = {};
  17904. }
  17905. /**
  17906. * Returns a render object for the given object and state data.
  17907. *
  17908. * @param {Object3D} object - The 3D object.
  17909. * @param {Material} material - The 3D object's material.
  17910. * @param {Scene} scene - The scene the 3D object belongs to.
  17911. * @param {Camera} camera - The camera the 3D object should be rendered with.
  17912. * @param {LightsNode} lightsNode - The lights node.
  17913. * @param {RenderContext} renderContext - The render context.
  17914. * @param {ClippingContext} clippingContext - The clipping context.
  17915. * @param {string} [passId] - An optional ID for identifying the pass.
  17916. * @return {RenderObject} The render object.
  17917. */
  17918. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  17919. const chainMap = this.getChainMap( passId );
  17920. // reuse chainArray
  17921. _chainKeys$5[ 0 ] = object;
  17922. _chainKeys$5[ 1 ] = material;
  17923. _chainKeys$5[ 2 ] = renderContext;
  17924. _chainKeys$5[ 3 ] = lightsNode;
  17925. let renderObject = chainMap.get( _chainKeys$5 );
  17926. if ( renderObject === undefined ) {
  17927. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  17928. chainMap.set( _chainKeys$5, renderObject );
  17929. } else {
  17930. renderObject.updateClipping( clippingContext );
  17931. if ( renderObject.needsGeometryUpdate ) {
  17932. renderObject.setGeometry( object.geometry );
  17933. }
  17934. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  17935. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  17936. renderObject.dispose();
  17937. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  17938. } else {
  17939. renderObject.version = material.version;
  17940. }
  17941. }
  17942. }
  17943. _chainKeys$5.length = 0;
  17944. return renderObject;
  17945. }
  17946. /**
  17947. * Returns a chain map for the given pass ID.
  17948. *
  17949. * @param {string} [passId='default'] - The pass ID.
  17950. * @return {ChainMap} The chain map.
  17951. */
  17952. getChainMap( passId = 'default' ) {
  17953. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  17954. }
  17955. /**
  17956. * Frees internal resources.
  17957. */
  17958. dispose() {
  17959. this.chainMaps = {};
  17960. }
  17961. /**
  17962. * Factory method for creating render objects with the given list of parameters.
  17963. *
  17964. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17965. * @param {Geometries} geometries - Renderer component for managing geometries.
  17966. * @param {Renderer} renderer - The renderer.
  17967. * @param {Object3D} object - The 3D object.
  17968. * @param {Material} material - The object's material.
  17969. * @param {Scene} scene - The scene the 3D object belongs to.
  17970. * @param {Camera} camera - The camera the object should be rendered with.
  17971. * @param {LightsNode} lightsNode - The lights node.
  17972. * @param {RenderContext} renderContext - The render context.
  17973. * @param {ClippingContext} clippingContext - The clipping context.
  17974. * @param {string} [passId] - An optional ID for identifying the pass.
  17975. * @return {RenderObject} The render object.
  17976. */
  17977. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  17978. const chainMap = this.getChainMap( passId );
  17979. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  17980. renderObject.onDispose = () => {
  17981. this.pipelines.delete( renderObject );
  17982. this.bindings.delete( renderObject );
  17983. this.nodes.delete( renderObject );
  17984. chainMap.delete( renderObject.getChainArray() );
  17985. };
  17986. return renderObject;
  17987. }
  17988. }
  17989. /**
  17990. * Data structure for the renderer. It is intended to manage
  17991. * data of objects in dictionaries.
  17992. *
  17993. * @private
  17994. */
  17995. class DataMap {
  17996. /**
  17997. * Constructs a new data map.
  17998. */
  17999. constructor() {
  18000. /**
  18001. * `DataMap` internally uses a weak map
  18002. * to manage its data.
  18003. *
  18004. * @type {WeakMap}
  18005. */
  18006. this.data = new WeakMap();
  18007. }
  18008. /**
  18009. * Returns the dictionary for the given object.
  18010. *
  18011. * @param {Object} object - The object.
  18012. * @return {Object} The dictionary.
  18013. */
  18014. get( object ) {
  18015. let map = this.data.get( object );
  18016. if ( map === undefined ) {
  18017. map = {};
  18018. this.data.set( object, map );
  18019. }
  18020. return map;
  18021. }
  18022. /**
  18023. * Deletes the dictionary for the given object.
  18024. *
  18025. * @param {Object} object - The object.
  18026. * @return {?Object} The deleted dictionary.
  18027. */
  18028. delete( object ) {
  18029. let map = null;
  18030. if ( this.data.has( object ) ) {
  18031. map = this.data.get( object );
  18032. this.data.delete( object );
  18033. }
  18034. return map;
  18035. }
  18036. /**
  18037. * Returns `true` if the given object has a dictionary defined.
  18038. *
  18039. * @param {Object} object - The object to test.
  18040. * @return {boolean} Whether a dictionary is defined or not.
  18041. */
  18042. has( object ) {
  18043. return this.data.has( object );
  18044. }
  18045. /**
  18046. * Frees internal resources.
  18047. */
  18048. dispose() {
  18049. this.data = new WeakMap();
  18050. }
  18051. }
  18052. const AttributeType = {
  18053. VERTEX: 1,
  18054. INDEX: 2,
  18055. STORAGE: 3,
  18056. INDIRECT: 4
  18057. };
  18058. // size of a chunk in bytes (STD140 layout)
  18059. const GPU_CHUNK_BYTES = 16;
  18060. // @TODO: Move to src/constants.js
  18061. const BlendColorFactor = 211;
  18062. const OneMinusBlendColorFactor = 212;
  18063. /**
  18064. * This renderer module manages geometry attributes.
  18065. *
  18066. * @private
  18067. * @augments DataMap
  18068. */
  18069. class Attributes extends DataMap {
  18070. /**
  18071. * Constructs a new attribute management component.
  18072. *
  18073. * @param {Backend} backend - The renderer's backend.
  18074. */
  18075. constructor( backend ) {
  18076. super();
  18077. /**
  18078. * The renderer's backend.
  18079. *
  18080. * @type {Backend}
  18081. */
  18082. this.backend = backend;
  18083. }
  18084. /**
  18085. * Deletes the data for the given attribute.
  18086. *
  18087. * @param {BufferAttribute} attribute - The attribute.
  18088. * @return {Object|null} The deleted attribute data.
  18089. */
  18090. delete( attribute ) {
  18091. const attributeData = super.delete( attribute );
  18092. if ( attributeData !== null ) {
  18093. this.backend.destroyAttribute( attribute );
  18094. }
  18095. return attributeData;
  18096. }
  18097. /**
  18098. * Updates the given attribute. This method creates attribute buffers
  18099. * for new attributes and updates data for existing ones.
  18100. *
  18101. * @param {BufferAttribute} attribute - The attribute to update.
  18102. * @param {number} type - The attribute type.
  18103. */
  18104. update( attribute, type ) {
  18105. const data = this.get( attribute );
  18106. if ( data.version === undefined ) {
  18107. if ( type === AttributeType.VERTEX ) {
  18108. this.backend.createAttribute( attribute );
  18109. } else if ( type === AttributeType.INDEX ) {
  18110. this.backend.createIndexAttribute( attribute );
  18111. } else if ( type === AttributeType.STORAGE ) {
  18112. this.backend.createStorageAttribute( attribute );
  18113. } else if ( type === AttributeType.INDIRECT ) {
  18114. this.backend.createIndirectStorageAttribute( attribute );
  18115. }
  18116. data.version = this._getBufferAttribute( attribute ).version;
  18117. } else {
  18118. const bufferAttribute = this._getBufferAttribute( attribute );
  18119. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  18120. this.backend.updateAttribute( attribute );
  18121. data.version = bufferAttribute.version;
  18122. }
  18123. }
  18124. }
  18125. /**
  18126. * Utility method for handling interleaved buffer attributes correctly.
  18127. * To process them, their `InterleavedBuffer` is returned.
  18128. *
  18129. * @param {BufferAttribute} attribute - The attribute.
  18130. * @return {BufferAttribute|InterleavedBuffer}
  18131. */
  18132. _getBufferAttribute( attribute ) {
  18133. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  18134. return attribute;
  18135. }
  18136. }
  18137. /**
  18138. * Returns the wireframe version for the given geometry.
  18139. *
  18140. * @private
  18141. * @function
  18142. * @param {BufferGeometry} geometry - The geometry.
  18143. * @return {number} The version.
  18144. */
  18145. function getWireframeVersion( geometry ) {
  18146. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  18147. }
  18148. /**
  18149. * Returns a wireframe index attribute for the given geometry.
  18150. *
  18151. * @private
  18152. * @function
  18153. * @param {BufferGeometry} geometry - The geometry.
  18154. * @return {BufferAttribute} The wireframe index attribute.
  18155. */
  18156. function getWireframeIndex( geometry ) {
  18157. const indices = [];
  18158. const geometryIndex = geometry.index;
  18159. const geometryPosition = geometry.attributes.position;
  18160. if ( geometryIndex !== null ) {
  18161. const array = geometryIndex.array;
  18162. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  18163. const a = array[ i + 0 ];
  18164. const b = array[ i + 1 ];
  18165. const c = array[ i + 2 ];
  18166. indices.push( a, b, b, c, c, a );
  18167. }
  18168. } else {
  18169. const array = geometryPosition.array;
  18170. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  18171. const a = i + 0;
  18172. const b = i + 1;
  18173. const c = i + 2;
  18174. indices.push( a, b, b, c, c, a );
  18175. }
  18176. }
  18177. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  18178. attribute.version = getWireframeVersion( geometry );
  18179. return attribute;
  18180. }
  18181. /**
  18182. * This renderer module manages geometries.
  18183. *
  18184. * @private
  18185. * @augments DataMap
  18186. */
  18187. class Geometries extends DataMap {
  18188. /**
  18189. * Constructs a new geometry management component.
  18190. *
  18191. * @param {Attributes} attributes - Renderer component for managing attributes.
  18192. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18193. */
  18194. constructor( attributes, info ) {
  18195. super();
  18196. /**
  18197. * Renderer component for managing attributes.
  18198. *
  18199. * @type {Attributes}
  18200. */
  18201. this.attributes = attributes;
  18202. /**
  18203. * Renderer component for managing metrics and monitoring data.
  18204. *
  18205. * @type {Info}
  18206. */
  18207. this.info = info;
  18208. /**
  18209. * Weak Map for managing attributes for wireframe rendering.
  18210. *
  18211. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  18212. */
  18213. this.wireframes = new WeakMap();
  18214. /**
  18215. * This Weak Map is used to make sure buffer attributes are
  18216. * updated only once per render call.
  18217. *
  18218. * @type {WeakMap<BufferAttribute,number>}
  18219. */
  18220. this.attributeCall = new WeakMap();
  18221. }
  18222. /**
  18223. * Returns `true` if the given render object has an initialized geometry.
  18224. *
  18225. * @param {RenderObject} renderObject - The render object.
  18226. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  18227. */
  18228. has( renderObject ) {
  18229. const geometry = renderObject.geometry;
  18230. return super.has( geometry ) && this.get( geometry ).initialized === true;
  18231. }
  18232. /**
  18233. * Prepares the geometry of the given render object for rendering.
  18234. *
  18235. * @param {RenderObject} renderObject - The render object.
  18236. */
  18237. updateForRender( renderObject ) {
  18238. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  18239. this.updateAttributes( renderObject );
  18240. }
  18241. /**
  18242. * Initializes the geometry of the given render object.
  18243. *
  18244. * @param {RenderObject} renderObject - The render object.
  18245. */
  18246. initGeometry( renderObject ) {
  18247. const geometry = renderObject.geometry;
  18248. const geometryData = this.get( geometry );
  18249. geometryData.initialized = true;
  18250. this.info.memory.geometries ++;
  18251. const onDispose = () => {
  18252. this.info.memory.geometries --;
  18253. const index = geometry.index;
  18254. const geometryAttributes = renderObject.getAttributes();
  18255. if ( index !== null ) {
  18256. this.attributes.delete( index );
  18257. }
  18258. for ( const geometryAttribute of geometryAttributes ) {
  18259. this.attributes.delete( geometryAttribute );
  18260. }
  18261. const wireframeAttribute = this.wireframes.get( geometry );
  18262. if ( wireframeAttribute !== undefined ) {
  18263. this.attributes.delete( wireframeAttribute );
  18264. }
  18265. geometry.removeEventListener( 'dispose', onDispose );
  18266. };
  18267. geometry.addEventListener( 'dispose', onDispose );
  18268. }
  18269. /**
  18270. * Updates the geometry attributes of the given render object.
  18271. *
  18272. * @param {RenderObject} renderObject - The render object.
  18273. */
  18274. updateAttributes( renderObject ) {
  18275. // attributes
  18276. const attributes = renderObject.getAttributes();
  18277. for ( const attribute of attributes ) {
  18278. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  18279. this.updateAttribute( attribute, AttributeType.STORAGE );
  18280. } else {
  18281. this.updateAttribute( attribute, AttributeType.VERTEX );
  18282. }
  18283. }
  18284. // indexes
  18285. const index = this.getIndex( renderObject );
  18286. if ( index !== null ) {
  18287. this.updateAttribute( index, AttributeType.INDEX );
  18288. }
  18289. // indirect
  18290. const indirect = renderObject.geometry.indirect;
  18291. if ( indirect !== null ) {
  18292. this.updateAttribute( indirect, AttributeType.INDIRECT );
  18293. }
  18294. }
  18295. /**
  18296. * Updates the given attribute.
  18297. *
  18298. * @param {BufferAttribute} attribute - The attribute to update.
  18299. * @param {number} type - The attribute type.
  18300. */
  18301. updateAttribute( attribute, type ) {
  18302. const callId = this.info.render.calls;
  18303. if ( ! attribute.isInterleavedBufferAttribute ) {
  18304. if ( this.attributeCall.get( attribute ) !== callId ) {
  18305. this.attributes.update( attribute, type );
  18306. this.attributeCall.set( attribute, callId );
  18307. }
  18308. } else {
  18309. if ( this.attributeCall.get( attribute ) === undefined ) {
  18310. this.attributes.update( attribute, type );
  18311. this.attributeCall.set( attribute, callId );
  18312. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  18313. this.attributes.update( attribute, type );
  18314. this.attributeCall.set( attribute.data, callId );
  18315. this.attributeCall.set( attribute, callId );
  18316. }
  18317. }
  18318. }
  18319. /**
  18320. * Returns the indirect buffer attribute of the given render object.
  18321. *
  18322. * @param {RenderObject} renderObject - The render object.
  18323. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  18324. */
  18325. getIndirect( renderObject ) {
  18326. return renderObject.geometry.indirect;
  18327. }
  18328. /**
  18329. * Returns the index of the given render object's geometry. This is implemented
  18330. * in a method to return a wireframe index if necessary.
  18331. *
  18332. * @param {RenderObject} renderObject - The render object.
  18333. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  18334. */
  18335. getIndex( renderObject ) {
  18336. const { geometry, material } = renderObject;
  18337. let index = geometry.index;
  18338. if ( material.wireframe === true ) {
  18339. const wireframes = this.wireframes;
  18340. let wireframeAttribute = wireframes.get( geometry );
  18341. if ( wireframeAttribute === undefined ) {
  18342. wireframeAttribute = getWireframeIndex( geometry );
  18343. wireframes.set( geometry, wireframeAttribute );
  18344. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  18345. this.attributes.delete( wireframeAttribute );
  18346. wireframeAttribute = getWireframeIndex( geometry );
  18347. wireframes.set( geometry, wireframeAttribute );
  18348. }
  18349. index = wireframeAttribute;
  18350. }
  18351. return index;
  18352. }
  18353. }
  18354. /**
  18355. * This renderer module provides a series of statistical information
  18356. * about the GPU memory and the rendering process. Useful for debugging
  18357. * and monitoring.
  18358. */
  18359. class Info {
  18360. /**
  18361. * Constructs a new info component.
  18362. */
  18363. constructor() {
  18364. /**
  18365. * Whether frame related metrics should automatically
  18366. * be resetted or not. This property should be set to `false`
  18367. * by apps which manage their own animation loop. They must
  18368. * then call `renderer.info.reset()` once per frame manually.
  18369. *
  18370. * @type {boolean}
  18371. * @default true
  18372. */
  18373. this.autoReset = true;
  18374. /**
  18375. * The current frame ID. This ID is managed
  18376. * by `NodeFrame`.
  18377. *
  18378. * @type {number}
  18379. * @readonly
  18380. * @default 0
  18381. */
  18382. this.frame = 0;
  18383. /**
  18384. * The number of render calls since the
  18385. * app has been started.
  18386. *
  18387. * @type {number}
  18388. * @readonly
  18389. * @default 0
  18390. */
  18391. this.calls = 0;
  18392. /**
  18393. * Render related metrics.
  18394. *
  18395. * @type {Object}
  18396. * @readonly
  18397. * @property {number} calls - The number of render calls since the app has been started.
  18398. * @property {number} frameCalls - The number of render calls of the current frame.
  18399. * @property {number} drawCalls - The number of draw calls of the current frame.
  18400. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  18401. * @property {number} points - The number of rendered point primitives of the current frame.
  18402. * @property {number} lines - The number of rendered line primitives of the current frame.
  18403. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  18404. */
  18405. this.render = {
  18406. calls: 0,
  18407. frameCalls: 0,
  18408. drawCalls: 0,
  18409. triangles: 0,
  18410. points: 0,
  18411. lines: 0,
  18412. timestamp: 0,
  18413. };
  18414. /**
  18415. * Compute related metrics.
  18416. *
  18417. * @type {Object}
  18418. * @readonly
  18419. * @property {number} calls - The number of compute calls since the app has been started.
  18420. * @property {number} frameCalls - The number of compute calls of the current frame.
  18421. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  18422. */
  18423. this.compute = {
  18424. calls: 0,
  18425. frameCalls: 0,
  18426. timestamp: 0
  18427. };
  18428. /**
  18429. * Memory related metrics.
  18430. *
  18431. * @type {Object}
  18432. * @readonly
  18433. * @property {number} geometries - The number of active geometries.
  18434. * @property {number} frameCalls - The number of active textures.
  18435. */
  18436. this.memory = {
  18437. geometries: 0,
  18438. textures: 0
  18439. };
  18440. }
  18441. /**
  18442. * This method should be executed per draw call and updates the corresponding metrics.
  18443. *
  18444. * @param {Object3D} object - The 3D object that is going to be rendered.
  18445. * @param {number} count - The vertex or index count.
  18446. * @param {number} instanceCount - The instance count.
  18447. */
  18448. update( object, count, instanceCount ) {
  18449. this.render.drawCalls ++;
  18450. if ( object.isMesh || object.isSprite ) {
  18451. this.render.triangles += instanceCount * ( count / 3 );
  18452. } else if ( object.isPoints ) {
  18453. this.render.points += instanceCount * count;
  18454. } else if ( object.isLineSegments ) {
  18455. this.render.lines += instanceCount * ( count / 2 );
  18456. } else if ( object.isLine ) {
  18457. this.render.lines += instanceCount * ( count - 1 );
  18458. } else {
  18459. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  18460. }
  18461. }
  18462. /**
  18463. * Resets frame related metrics.
  18464. */
  18465. reset() {
  18466. this.render.drawCalls = 0;
  18467. this.render.frameCalls = 0;
  18468. this.compute.frameCalls = 0;
  18469. this.render.triangles = 0;
  18470. this.render.points = 0;
  18471. this.render.lines = 0;
  18472. }
  18473. /**
  18474. * Performs a complete reset of the object.
  18475. */
  18476. dispose() {
  18477. this.reset();
  18478. this.calls = 0;
  18479. this.render.calls = 0;
  18480. this.compute.calls = 0;
  18481. this.render.timestamp = 0;
  18482. this.compute.timestamp = 0;
  18483. this.memory.geometries = 0;
  18484. this.memory.textures = 0;
  18485. }
  18486. }
  18487. /**
  18488. * Abstract class for representing pipelines.
  18489. *
  18490. * @private
  18491. * @abstract
  18492. */
  18493. class Pipeline {
  18494. /**
  18495. * Constructs a new pipeline.
  18496. *
  18497. * @param {string} cacheKey - The pipeline's cache key.
  18498. */
  18499. constructor( cacheKey ) {
  18500. /**
  18501. * The pipeline's cache key.
  18502. *
  18503. * @type {string}
  18504. */
  18505. this.cacheKey = cacheKey;
  18506. /**
  18507. * How often the pipeline is currently in use.
  18508. *
  18509. * @type {number}
  18510. * @default 0
  18511. */
  18512. this.usedTimes = 0;
  18513. }
  18514. }
  18515. /**
  18516. * Class for representing render pipelines.
  18517. *
  18518. * @private
  18519. * @augments Pipeline
  18520. */
  18521. class RenderPipeline extends Pipeline {
  18522. /**
  18523. * Constructs a new render pipeline.
  18524. *
  18525. * @param {string} cacheKey - The pipeline's cache key.
  18526. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  18527. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  18528. */
  18529. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  18530. super( cacheKey );
  18531. /**
  18532. * The pipeline's vertex shader.
  18533. *
  18534. * @type {ProgrammableStage}
  18535. */
  18536. this.vertexProgram = vertexProgram;
  18537. /**
  18538. * The pipeline's fragment shader.
  18539. *
  18540. * @type {ProgrammableStage}
  18541. */
  18542. this.fragmentProgram = fragmentProgram;
  18543. }
  18544. }
  18545. /**
  18546. * Class for representing compute pipelines.
  18547. *
  18548. * @private
  18549. * @augments Pipeline
  18550. */
  18551. class ComputePipeline extends Pipeline {
  18552. /**
  18553. * Constructs a new render pipeline.
  18554. *
  18555. * @param {string} cacheKey - The pipeline's cache key.
  18556. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  18557. */
  18558. constructor( cacheKey, computeProgram ) {
  18559. super( cacheKey );
  18560. /**
  18561. * The pipeline's compute shader.
  18562. *
  18563. * @type {ProgrammableStage}
  18564. */
  18565. this.computeProgram = computeProgram;
  18566. /**
  18567. * This flag can be used for type testing.
  18568. *
  18569. * @type {boolean}
  18570. * @readonly
  18571. * @default true
  18572. */
  18573. this.isComputePipeline = true;
  18574. }
  18575. }
  18576. let _id$8 = 0;
  18577. /**
  18578. * Class for representing programmable stages which are vertex,
  18579. * fragment or compute shaders. Unlike fixed-function states (like blending),
  18580. * they represent the programmable part of a pipeline.
  18581. *
  18582. * @private
  18583. */
  18584. class ProgrammableStage {
  18585. /**
  18586. * Constructs a new programmable stage.
  18587. *
  18588. * @param {string} code - The shader code.
  18589. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  18590. * @param {string} name - The name of the shader.
  18591. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  18592. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  18593. */
  18594. constructor( code, stage, name, transforms = null, attributes = null ) {
  18595. /**
  18596. * The id of the programmable stage.
  18597. *
  18598. * @type {number}
  18599. */
  18600. this.id = _id$8 ++;
  18601. /**
  18602. * The shader code.
  18603. *
  18604. * @type {string}
  18605. */
  18606. this.code = code;
  18607. /**
  18608. * The type of stage.
  18609. *
  18610. * @type {string}
  18611. */
  18612. this.stage = stage;
  18613. /**
  18614. * The name of the stage.
  18615. * This is used for debugging purposes.
  18616. *
  18617. * @type {string}
  18618. */
  18619. this.name = name;
  18620. /**
  18621. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  18622. *
  18623. * @type {?Array<Object>}
  18624. */
  18625. this.transforms = transforms;
  18626. /**
  18627. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  18628. *
  18629. * @type {?Array<Object>}
  18630. */
  18631. this.attributes = attributes;
  18632. /**
  18633. * How often the programmable stage is currently in use.
  18634. *
  18635. * @type {number}
  18636. * @default 0
  18637. */
  18638. this.usedTimes = 0;
  18639. }
  18640. }
  18641. /**
  18642. * This renderer module manages the pipelines of the renderer.
  18643. *
  18644. * @private
  18645. * @augments DataMap
  18646. */
  18647. class Pipelines extends DataMap {
  18648. /**
  18649. * Constructs a new pipeline management component.
  18650. *
  18651. * @param {Backend} backend - The renderer's backend.
  18652. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18653. */
  18654. constructor( backend, nodes ) {
  18655. super();
  18656. /**
  18657. * The renderer's backend.
  18658. *
  18659. * @type {Backend}
  18660. */
  18661. this.backend = backend;
  18662. /**
  18663. * Renderer component for managing nodes related logic.
  18664. *
  18665. * @type {Nodes}
  18666. */
  18667. this.nodes = nodes;
  18668. /**
  18669. * A references to the bindings management component.
  18670. * This reference will be set inside the `Bindings`
  18671. * constructor.
  18672. *
  18673. * @type {?Bindings}
  18674. * @default null
  18675. */
  18676. this.bindings = null;
  18677. /**
  18678. * Internal cache for maintaining pipelines.
  18679. * The key of the map is a cache key, the value the pipeline.
  18680. *
  18681. * @type {Map<string,Pipeline>}
  18682. */
  18683. this.caches = new Map();
  18684. /**
  18685. * This dictionary maintains for each shader stage type (vertex,
  18686. * fragment and compute) the programmable stage objects which
  18687. * represent the actual shader code.
  18688. *
  18689. * @type {Object<string,Map>}
  18690. */
  18691. this.programs = {
  18692. vertex: new Map(),
  18693. fragment: new Map(),
  18694. compute: new Map()
  18695. };
  18696. }
  18697. /**
  18698. * Returns a compute pipeline for the given compute node.
  18699. *
  18700. * @param {Node} computeNode - The compute node.
  18701. * @param {Array<BindGroup>} bindings - The bindings.
  18702. * @return {ComputePipeline} The compute pipeline.
  18703. */
  18704. getForCompute( computeNode, bindings ) {
  18705. const { backend } = this;
  18706. const data = this.get( computeNode );
  18707. if ( this._needsComputeUpdate( computeNode ) ) {
  18708. const previousPipeline = data.pipeline;
  18709. if ( previousPipeline ) {
  18710. previousPipeline.usedTimes --;
  18711. previousPipeline.computeProgram.usedTimes --;
  18712. }
  18713. // get shader
  18714. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  18715. // programmable stage
  18716. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  18717. if ( stageCompute === undefined ) {
  18718. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  18719. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  18720. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  18721. backend.createProgram( stageCompute );
  18722. }
  18723. // determine compute pipeline
  18724. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  18725. let pipeline = this.caches.get( cacheKey );
  18726. if ( pipeline === undefined ) {
  18727. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  18728. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  18729. }
  18730. // keep track of all used times
  18731. pipeline.usedTimes ++;
  18732. stageCompute.usedTimes ++;
  18733. //
  18734. data.version = computeNode.version;
  18735. data.pipeline = pipeline;
  18736. }
  18737. return data.pipeline;
  18738. }
  18739. /**
  18740. * Returns a render pipeline for the given render object.
  18741. *
  18742. * @param {RenderObject} renderObject - The render object.
  18743. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  18744. * @return {RenderPipeline} The render pipeline.
  18745. */
  18746. getForRender( renderObject, promises = null ) {
  18747. const { backend } = this;
  18748. const data = this.get( renderObject );
  18749. if ( this._needsRenderUpdate( renderObject ) ) {
  18750. const previousPipeline = data.pipeline;
  18751. if ( previousPipeline ) {
  18752. previousPipeline.usedTimes --;
  18753. previousPipeline.vertexProgram.usedTimes --;
  18754. previousPipeline.fragmentProgram.usedTimes --;
  18755. }
  18756. // get shader
  18757. const nodeBuilderState = renderObject.getNodeBuilderState();
  18758. const name = renderObject.material ? renderObject.material.name : '';
  18759. // programmable stages
  18760. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  18761. if ( stageVertex === undefined ) {
  18762. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  18763. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  18764. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  18765. backend.createProgram( stageVertex );
  18766. }
  18767. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  18768. if ( stageFragment === undefined ) {
  18769. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  18770. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  18771. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  18772. backend.createProgram( stageFragment );
  18773. }
  18774. // determine render pipeline
  18775. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  18776. let pipeline = this.caches.get( cacheKey );
  18777. if ( pipeline === undefined ) {
  18778. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  18779. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  18780. } else {
  18781. renderObject.pipeline = pipeline;
  18782. }
  18783. // keep track of all used times
  18784. pipeline.usedTimes ++;
  18785. stageVertex.usedTimes ++;
  18786. stageFragment.usedTimes ++;
  18787. //
  18788. data.pipeline = pipeline;
  18789. }
  18790. return data.pipeline;
  18791. }
  18792. /**
  18793. * Deletes the pipeline for the given render object.
  18794. *
  18795. * @param {RenderObject} object - The render object.
  18796. * @return {?Object} The deleted dictionary.
  18797. */
  18798. delete( object ) {
  18799. const pipeline = this.get( object ).pipeline;
  18800. if ( pipeline ) {
  18801. // pipeline
  18802. pipeline.usedTimes --;
  18803. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  18804. // programs
  18805. if ( pipeline.isComputePipeline ) {
  18806. pipeline.computeProgram.usedTimes --;
  18807. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  18808. } else {
  18809. pipeline.fragmentProgram.usedTimes --;
  18810. pipeline.vertexProgram.usedTimes --;
  18811. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  18812. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  18813. }
  18814. }
  18815. return super.delete( object );
  18816. }
  18817. /**
  18818. * Frees internal resources.
  18819. */
  18820. dispose() {
  18821. super.dispose();
  18822. this.caches = new Map();
  18823. this.programs = {
  18824. vertex: new Map(),
  18825. fragment: new Map(),
  18826. compute: new Map()
  18827. };
  18828. }
  18829. /**
  18830. * Updates the pipeline for the given render object.
  18831. *
  18832. * @param {RenderObject} renderObject - The render object.
  18833. */
  18834. updateForRender( renderObject ) {
  18835. this.getForRender( renderObject );
  18836. }
  18837. /**
  18838. * Returns a compute pipeline for the given parameters.
  18839. *
  18840. * @private
  18841. * @param {Node} computeNode - The compute node.
  18842. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  18843. * @param {string} cacheKey - The cache key.
  18844. * @param {Array<BindGroup>} bindings - The bindings.
  18845. * @return {ComputePipeline} The compute pipeline.
  18846. */
  18847. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  18848. // check for existing pipeline
  18849. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  18850. let pipeline = this.caches.get( cacheKey );
  18851. if ( pipeline === undefined ) {
  18852. pipeline = new ComputePipeline( cacheKey, stageCompute );
  18853. this.caches.set( cacheKey, pipeline );
  18854. this.backend.createComputePipeline( pipeline, bindings );
  18855. }
  18856. return pipeline;
  18857. }
  18858. /**
  18859. * Returns a render pipeline for the given parameters.
  18860. *
  18861. * @private
  18862. * @param {RenderObject} renderObject - The render object.
  18863. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  18864. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  18865. * @param {string} cacheKey - The cache key.
  18866. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  18867. * @return {ComputePipeline} The compute pipeline.
  18868. */
  18869. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  18870. // check for existing pipeline
  18871. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  18872. let pipeline = this.caches.get( cacheKey );
  18873. if ( pipeline === undefined ) {
  18874. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  18875. this.caches.set( cacheKey, pipeline );
  18876. renderObject.pipeline = pipeline;
  18877. // The `promises` array is `null` by default and only set to an empty array when
  18878. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  18879. // pending promises that resolve when the render pipelines are ready for rendering.
  18880. this.backend.createRenderPipeline( renderObject, promises );
  18881. }
  18882. return pipeline;
  18883. }
  18884. /**
  18885. * Computes a cache key representing a compute pipeline.
  18886. *
  18887. * @private
  18888. * @param {Node} computeNode - The compute node.
  18889. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  18890. * @return {string} The cache key.
  18891. */
  18892. _getComputeCacheKey( computeNode, stageCompute ) {
  18893. return computeNode.id + ',' + stageCompute.id;
  18894. }
  18895. /**
  18896. * Computes a cache key representing a render pipeline.
  18897. *
  18898. * @private
  18899. * @param {RenderObject} renderObject - The render object.
  18900. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  18901. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  18902. * @return {string} The cache key.
  18903. */
  18904. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  18905. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  18906. }
  18907. /**
  18908. * Releases the given pipeline.
  18909. *
  18910. * @private
  18911. * @param {Pipeline} pipeline - The pipeline to release.
  18912. */
  18913. _releasePipeline( pipeline ) {
  18914. this.caches.delete( pipeline.cacheKey );
  18915. }
  18916. /**
  18917. * Releases the shader program.
  18918. *
  18919. * @private
  18920. * @param {Object} program - The shader program to release.
  18921. */
  18922. _releaseProgram( program ) {
  18923. const code = program.code;
  18924. const stage = program.stage;
  18925. this.programs[ stage ].delete( code );
  18926. }
  18927. /**
  18928. * Returns `true` if the compute pipeline for the given compute node requires an update.
  18929. *
  18930. * @private
  18931. * @param {Node} computeNode - The compute node.
  18932. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  18933. */
  18934. _needsComputeUpdate( computeNode ) {
  18935. const data = this.get( computeNode );
  18936. return data.pipeline === undefined || data.version !== computeNode.version;
  18937. }
  18938. /**
  18939. * Returns `true` if the render pipeline for the given render object requires an update.
  18940. *
  18941. * @private
  18942. * @param {RenderObject} renderObject - The render object.
  18943. * @return {boolean} Whether the render object for the given render object requires an update or not.
  18944. */
  18945. _needsRenderUpdate( renderObject ) {
  18946. const data = this.get( renderObject );
  18947. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  18948. }
  18949. }
  18950. /**
  18951. * This renderer module manages the bindings of the renderer.
  18952. *
  18953. * @private
  18954. * @augments DataMap
  18955. */
  18956. class Bindings extends DataMap {
  18957. /**
  18958. * Constructs a new bindings management component.
  18959. *
  18960. * @param {Backend} backend - The renderer's backend.
  18961. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18962. * @param {Textures} textures - Renderer component for managing textures.
  18963. * @param {Attributes} attributes - Renderer component for managing attributes.
  18964. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  18965. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18966. */
  18967. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  18968. super();
  18969. /**
  18970. * The renderer's backend.
  18971. *
  18972. * @type {Backend}
  18973. */
  18974. this.backend = backend;
  18975. /**
  18976. * Renderer component for managing textures.
  18977. *
  18978. * @type {Textures}
  18979. */
  18980. this.textures = textures;
  18981. /**
  18982. * Renderer component for managing pipelines.
  18983. *
  18984. * @type {Pipelines}
  18985. */
  18986. this.pipelines = pipelines;
  18987. /**
  18988. * Renderer component for managing attributes.
  18989. *
  18990. * @type {Attributes}
  18991. */
  18992. this.attributes = attributes;
  18993. /**
  18994. * Renderer component for managing nodes related logic.
  18995. *
  18996. * @type {Nodes}
  18997. */
  18998. this.nodes = nodes;
  18999. /**
  19000. * Renderer component for managing metrics and monitoring data.
  19001. *
  19002. * @type {Info}
  19003. */
  19004. this.info = info;
  19005. this.pipelines.bindings = this; // assign bindings to pipelines
  19006. }
  19007. /**
  19008. * Returns the bind groups for the given render object.
  19009. *
  19010. * @param {RenderObject} renderObject - The render object.
  19011. * @return {Array<BindGroup>} The bind groups.
  19012. */
  19013. getForRender( renderObject ) {
  19014. const bindings = renderObject.getBindings();
  19015. for ( const bindGroup of bindings ) {
  19016. const groupData = this.get( bindGroup );
  19017. if ( groupData.bindGroup === undefined ) {
  19018. // each object defines an array of bindings (ubos, textures, samplers etc.)
  19019. this._init( bindGroup );
  19020. this.backend.createBindings( bindGroup, bindings, 0 );
  19021. groupData.bindGroup = bindGroup;
  19022. }
  19023. }
  19024. return bindings;
  19025. }
  19026. /**
  19027. * Returns the bind groups for the given compute node.
  19028. *
  19029. * @param {Node} computeNode - The compute node.
  19030. * @return {Array<BindGroup>} The bind groups.
  19031. */
  19032. getForCompute( computeNode ) {
  19033. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  19034. for ( const bindGroup of bindings ) {
  19035. const groupData = this.get( bindGroup );
  19036. if ( groupData.bindGroup === undefined ) {
  19037. this._init( bindGroup );
  19038. this.backend.createBindings( bindGroup, bindings, 0 );
  19039. groupData.bindGroup = bindGroup;
  19040. }
  19041. }
  19042. return bindings;
  19043. }
  19044. /**
  19045. * Updates the bindings for the given compute node.
  19046. *
  19047. * @param {Node} computeNode - The compute node.
  19048. */
  19049. updateForCompute( computeNode ) {
  19050. this._updateBindings( this.getForCompute( computeNode ) );
  19051. }
  19052. /**
  19053. * Updates the bindings for the given render object.
  19054. *
  19055. * @param {RenderObject} renderObject - The render object.
  19056. */
  19057. updateForRender( renderObject ) {
  19058. this._updateBindings( this.getForRender( renderObject ) );
  19059. }
  19060. /**
  19061. * Updates the given array of bindings.
  19062. *
  19063. * @param {Array<BindGroup>} bindings - The bind groups.
  19064. */
  19065. _updateBindings( bindings ) {
  19066. for ( const bindGroup of bindings ) {
  19067. this._update( bindGroup, bindings );
  19068. }
  19069. }
  19070. /**
  19071. * Initializes the given bind group.
  19072. *
  19073. * @param {BindGroup} bindGroup - The bind group to initialize.
  19074. */
  19075. _init( bindGroup ) {
  19076. for ( const binding of bindGroup.bindings ) {
  19077. if ( binding.isSampledTexture ) {
  19078. this.textures.updateTexture( binding.texture );
  19079. } else if ( binding.isStorageBuffer ) {
  19080. const attribute = binding.attribute;
  19081. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  19082. this.attributes.update( attribute, attributeType );
  19083. }
  19084. }
  19085. }
  19086. /**
  19087. * Updates the given bind group.
  19088. *
  19089. * @param {BindGroup} bindGroup - The bind group to update.
  19090. * @param {Array<BindGroup>} bindings - The bind groups.
  19091. */
  19092. _update( bindGroup, bindings ) {
  19093. const { backend } = this;
  19094. let needsBindingsUpdate = false;
  19095. let cacheBindings = true;
  19096. let cacheIndex = 0;
  19097. let version = 0;
  19098. // iterate over all bindings and check if buffer updates or a new binding group is required
  19099. for ( const binding of bindGroup.bindings ) {
  19100. if ( binding.isNodeUniformsGroup ) {
  19101. const updated = this.nodes.updateGroup( binding );
  19102. // every uniforms group is a uniform buffer. So if no update is required,
  19103. // we move one with the next binding. Otherwise the next if block will update the group.
  19104. if ( updated === false ) continue;
  19105. }
  19106. if ( binding.isStorageBuffer ) {
  19107. const attribute = binding.attribute;
  19108. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  19109. this.attributes.update( attribute, attributeType );
  19110. }
  19111. if ( binding.isUniformBuffer ) {
  19112. const updated = binding.update();
  19113. if ( updated ) {
  19114. backend.updateBinding( binding );
  19115. }
  19116. } else if ( binding.isSampler ) {
  19117. binding.update();
  19118. } else if ( binding.isSampledTexture ) {
  19119. const texturesTextureData = this.textures.get( binding.texture );
  19120. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  19121. const updated = binding.update();
  19122. const texture = binding.texture;
  19123. if ( updated ) {
  19124. this.textures.updateTexture( texture );
  19125. }
  19126. const textureData = backend.get( texture );
  19127. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  19128. cacheBindings = false;
  19129. } else {
  19130. cacheIndex = cacheIndex * 10 + texture.id;
  19131. version += texture.version;
  19132. }
  19133. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  19134. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  19135. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  19136. this.textures.updateTexture( texture );
  19137. needsBindingsUpdate = true;
  19138. }
  19139. if ( texture.isStorageTexture === true ) {
  19140. const textureData = this.get( texture );
  19141. if ( binding.store === true ) {
  19142. textureData.needsMipmap = true;
  19143. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  19144. this.backend.generateMipmaps( texture );
  19145. textureData.needsMipmap = false;
  19146. }
  19147. }
  19148. }
  19149. }
  19150. if ( needsBindingsUpdate === true ) {
  19151. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  19152. }
  19153. }
  19154. }
  19155. /**
  19156. * Default sorting function for opaque render items.
  19157. *
  19158. * @private
  19159. * @function
  19160. * @param {Object} a - The first render item.
  19161. * @param {Object} b - The second render item.
  19162. * @return {number} A numeric value which defines the sort order.
  19163. */
  19164. function painterSortStable( a, b ) {
  19165. if ( a.groupOrder !== b.groupOrder ) {
  19166. return a.groupOrder - b.groupOrder;
  19167. } else if ( a.renderOrder !== b.renderOrder ) {
  19168. return a.renderOrder - b.renderOrder;
  19169. } else if ( a.material.id !== b.material.id ) {
  19170. return a.material.id - b.material.id;
  19171. } else if ( a.z !== b.z ) {
  19172. return a.z - b.z;
  19173. } else {
  19174. return a.id - b.id;
  19175. }
  19176. }
  19177. /**
  19178. * Default sorting function for transparent render items.
  19179. *
  19180. * @private
  19181. * @function
  19182. * @param {Object} a - The first render item.
  19183. * @param {Object} b - The second render item.
  19184. * @return {number} A numeric value which defines the sort order.
  19185. */
  19186. function reversePainterSortStable( a, b ) {
  19187. if ( a.groupOrder !== b.groupOrder ) {
  19188. return a.groupOrder - b.groupOrder;
  19189. } else if ( a.renderOrder !== b.renderOrder ) {
  19190. return a.renderOrder - b.renderOrder;
  19191. } else if ( a.z !== b.z ) {
  19192. return b.z - a.z;
  19193. } else {
  19194. return a.id - b.id;
  19195. }
  19196. }
  19197. /**
  19198. * Returns `true` if the given transparent material requires a double pass.
  19199. *
  19200. * @private
  19201. * @function
  19202. * @param {Material} material - The transparent material.
  19203. * @return {boolean} Whether the given material requires a double pass or not.
  19204. */
  19205. function needsDoublePass( material ) {
  19206. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  19207. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  19208. }
  19209. /**
  19210. * When the renderer analyzes the scene at the beginning of a render call,
  19211. * it stores 3D object for further processing in render lists. Depending on the
  19212. * properties of a 3D objects (like their transformation or material state), the
  19213. * objects are maintained in ordered lists for the actual rendering.
  19214. *
  19215. * Render lists are unique per scene and camera combination.
  19216. *
  19217. * @private
  19218. * @augments Pipeline
  19219. */
  19220. class RenderList {
  19221. /**
  19222. * Constructs a render list.
  19223. *
  19224. * @param {Lighting} lighting - The lighting management component.
  19225. * @param {Scene} scene - The scene.
  19226. * @param {Camera} camera - The camera the scene is rendered with.
  19227. */
  19228. constructor( lighting, scene, camera ) {
  19229. /**
  19230. * 3D objects are transformed into render items and stored in this array.
  19231. *
  19232. * @type {Array<Object>}
  19233. */
  19234. this.renderItems = [];
  19235. /**
  19236. * The current render items index.
  19237. *
  19238. * @type {number}
  19239. * @default 0
  19240. */
  19241. this.renderItemsIndex = 0;
  19242. /**
  19243. * A list with opaque render items.
  19244. *
  19245. * @type {Array<Object>}
  19246. */
  19247. this.opaque = [];
  19248. /**
  19249. * A list with transparent render items which require
  19250. * double pass rendering (e.g. transmissive objects).
  19251. *
  19252. * @type {Array<Object>}
  19253. */
  19254. this.transparentDoublePass = [];
  19255. /**
  19256. * A list with transparent render items.
  19257. *
  19258. * @type {Array<Object>}
  19259. */
  19260. this.transparent = [];
  19261. /**
  19262. * A list with transparent render bundle data.
  19263. *
  19264. * @type {Array<Object>}
  19265. */
  19266. this.bundles = [];
  19267. /**
  19268. * The render list's lights node. This node is later
  19269. * relevant for the actual analytical light nodes which
  19270. * compute the scene's lighting in the shader.
  19271. *
  19272. * @type {LightsNode}
  19273. */
  19274. this.lightsNode = lighting.getNode( scene, camera );
  19275. /**
  19276. * The scene's lights stored in an array. This array
  19277. * is used to setup the lights node.
  19278. *
  19279. * @type {Array<Light>}
  19280. */
  19281. this.lightsArray = [];
  19282. /**
  19283. * The scene.
  19284. *
  19285. * @type {Scene}
  19286. */
  19287. this.scene = scene;
  19288. /**
  19289. * The camera the scene is rendered with.
  19290. *
  19291. * @type {Camera}
  19292. */
  19293. this.camera = camera;
  19294. /**
  19295. * How many objects perform occlusion query tests.
  19296. *
  19297. * @type {number}
  19298. * @default 0
  19299. */
  19300. this.occlusionQueryCount = 0;
  19301. }
  19302. /**
  19303. * This method is called right at the beginning of a render call
  19304. * before the scene is analyzed. It prepares the internal data
  19305. * structures for the upcoming render lists generation.
  19306. *
  19307. * @return {RenderList} A reference to this render list.
  19308. */
  19309. begin() {
  19310. this.renderItemsIndex = 0;
  19311. this.opaque.length = 0;
  19312. this.transparentDoublePass.length = 0;
  19313. this.transparent.length = 0;
  19314. this.bundles.length = 0;
  19315. this.lightsArray.length = 0;
  19316. this.occlusionQueryCount = 0;
  19317. return this;
  19318. }
  19319. /**
  19320. * Returns a render item for the giving render item state. The state is defined
  19321. * by a series of object-related parameters.
  19322. *
  19323. * The method avoids object creation by holding render items and reusing them in
  19324. * subsequent render calls (just with different property values).
  19325. *
  19326. * @param {Object3D} object - The 3D object.
  19327. * @param {BufferGeometry} geometry - The 3D object's geometry.
  19328. * @param {Material} material - The 3D object's material.
  19329. * @param {number} groupOrder - The current group order.
  19330. * @param {number} z - Th 3D object's depth value (z value in clip space).
  19331. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  19332. * @param {ClippingContext} clippingContext - The current clipping context.
  19333. * @return {Object} The render item.
  19334. */
  19335. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  19336. let renderItem = this.renderItems[ this.renderItemsIndex ];
  19337. if ( renderItem === undefined ) {
  19338. renderItem = {
  19339. id: object.id,
  19340. object: object,
  19341. geometry: geometry,
  19342. material: material,
  19343. groupOrder: groupOrder,
  19344. renderOrder: object.renderOrder,
  19345. z: z,
  19346. group: group,
  19347. clippingContext: clippingContext
  19348. };
  19349. this.renderItems[ this.renderItemsIndex ] = renderItem;
  19350. } else {
  19351. renderItem.id = object.id;
  19352. renderItem.object = object;
  19353. renderItem.geometry = geometry;
  19354. renderItem.material = material;
  19355. renderItem.groupOrder = groupOrder;
  19356. renderItem.renderOrder = object.renderOrder;
  19357. renderItem.z = z;
  19358. renderItem.group = group;
  19359. renderItem.clippingContext = clippingContext;
  19360. }
  19361. this.renderItemsIndex ++;
  19362. return renderItem;
  19363. }
  19364. /**
  19365. * Pushes the given object as a render item to the internal render lists.
  19366. * The selected lists depend on the object properties.
  19367. *
  19368. * @param {Object3D} object - The 3D object.
  19369. * @param {BufferGeometry} geometry - The 3D object's geometry.
  19370. * @param {Material} material - The 3D object's material.
  19371. * @param {number} groupOrder - The current group order.
  19372. * @param {number} z - Th 3D object's depth value (z value in clip space).
  19373. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  19374. * @param {ClippingContext} clippingContext - The current clipping context.
  19375. */
  19376. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  19377. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  19378. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  19379. if ( material.transparent === true || material.transmission > 0 ) {
  19380. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  19381. this.transparent.push( renderItem );
  19382. } else {
  19383. this.opaque.push( renderItem );
  19384. }
  19385. }
  19386. /**
  19387. * Inserts the given object as a render item at the start of the internal render lists.
  19388. * The selected lists depend on the object properties.
  19389. *
  19390. * @param {Object3D} object - The 3D object.
  19391. * @param {BufferGeometry} geometry - The 3D object's geometry.
  19392. * @param {Material} material - The 3D object's material.
  19393. * @param {number} groupOrder - The current group order.
  19394. * @param {number} z - Th 3D object's depth value (z value in clip space).
  19395. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  19396. * @param {ClippingContext} clippingContext - The current clipping context.
  19397. */
  19398. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  19399. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  19400. if ( material.transparent === true || material.transmission > 0 ) {
  19401. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  19402. this.transparent.unshift( renderItem );
  19403. } else {
  19404. this.opaque.unshift( renderItem );
  19405. }
  19406. }
  19407. /**
  19408. * Pushes render bundle group data into the render list.
  19409. *
  19410. * @param {Object} group - Bundle group data.
  19411. */
  19412. pushBundle( group ) {
  19413. this.bundles.push( group );
  19414. }
  19415. /**
  19416. * Pushes a light into the render list.
  19417. *
  19418. * @param {Light} light - The light.
  19419. */
  19420. pushLight( light ) {
  19421. this.lightsArray.push( light );
  19422. }
  19423. /**
  19424. * Sorts the internal render lists.
  19425. *
  19426. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  19427. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  19428. */
  19429. sort( customOpaqueSort, customTransparentSort ) {
  19430. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  19431. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  19432. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  19433. }
  19434. /**
  19435. * This method performs finalizing tasks right after the render lists
  19436. * have been generated.
  19437. */
  19438. finish() {
  19439. // update lights
  19440. this.lightsNode.setLights( this.lightsArray );
  19441. // Clear references from inactive renderItems in the list
  19442. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  19443. const renderItem = this.renderItems[ i ];
  19444. if ( renderItem.id === null ) break;
  19445. renderItem.id = null;
  19446. renderItem.object = null;
  19447. renderItem.geometry = null;
  19448. renderItem.material = null;
  19449. renderItem.groupOrder = null;
  19450. renderItem.renderOrder = null;
  19451. renderItem.z = null;
  19452. renderItem.group = null;
  19453. renderItem.clippingContext = null;
  19454. }
  19455. }
  19456. }
  19457. const _chainKeys$4 = [];
  19458. /**
  19459. * This renderer module manages the render lists which are unique
  19460. * per scene and camera combination.
  19461. *
  19462. * @private
  19463. */
  19464. class RenderLists {
  19465. /**
  19466. * Constructs a render lists management component.
  19467. *
  19468. * @param {Lighting} lighting - The lighting management component.
  19469. */
  19470. constructor( lighting ) {
  19471. /**
  19472. * The lighting management component.
  19473. *
  19474. * @type {Lighting}
  19475. */
  19476. this.lighting = lighting;
  19477. /**
  19478. * The internal chain map which holds the render lists.
  19479. *
  19480. * @type {ChainMap}
  19481. */
  19482. this.lists = new ChainMap();
  19483. }
  19484. /**
  19485. * Returns a render list for the given scene and camera.
  19486. *
  19487. * @param {Scene} scene - The scene.
  19488. * @param {Camera} camera - The camera.
  19489. * @return {RenderList} The render list.
  19490. */
  19491. get( scene, camera ) {
  19492. const lists = this.lists;
  19493. _chainKeys$4[ 0 ] = scene;
  19494. _chainKeys$4[ 1 ] = camera;
  19495. let list = lists.get( _chainKeys$4 );
  19496. if ( list === undefined ) {
  19497. list = new RenderList( this.lighting, scene, camera );
  19498. lists.set( _chainKeys$4, list );
  19499. }
  19500. _chainKeys$4.length = 0;
  19501. return list;
  19502. }
  19503. /**
  19504. * Frees all internal resources.
  19505. */
  19506. dispose() {
  19507. this.lists = new ChainMap();
  19508. }
  19509. }
  19510. let _id$7 = 0;
  19511. /**
  19512. * Any render or compute command is executed in a specific context that defines
  19513. * the state of the renderer and its backend. Typical examples for such context
  19514. * data are the current clear values or data from the active framebuffer. This
  19515. * module is used to represent these contexts as objects.
  19516. *
  19517. * @private
  19518. */
  19519. class RenderContext {
  19520. /**
  19521. * Constructs a new render context.
  19522. */
  19523. constructor() {
  19524. /**
  19525. * The context's ID.
  19526. *
  19527. * @type {number}
  19528. */
  19529. this.id = _id$7 ++;
  19530. /**
  19531. * Whether the current active framebuffer has a color attachment.
  19532. *
  19533. * @type {boolean}
  19534. * @default true
  19535. */
  19536. this.color = true;
  19537. /**
  19538. * Whether the color attachment should be cleared or not.
  19539. *
  19540. * @type {boolean}
  19541. * @default true
  19542. */
  19543. this.clearColor = true;
  19544. /**
  19545. * The clear color value.
  19546. *
  19547. * @type {Object}
  19548. * @default true
  19549. */
  19550. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  19551. /**
  19552. * Whether the current active framebuffer has a depth attachment.
  19553. *
  19554. * @type {boolean}
  19555. * @default true
  19556. */
  19557. this.depth = true;
  19558. /**
  19559. * Whether the depth attachment should be cleared or not.
  19560. *
  19561. * @type {boolean}
  19562. * @default true
  19563. */
  19564. this.clearDepth = true;
  19565. /**
  19566. * The clear depth value.
  19567. *
  19568. * @type {number}
  19569. * @default 1
  19570. */
  19571. this.clearDepthValue = 1;
  19572. /**
  19573. * Whether the current active framebuffer has a stencil attachment.
  19574. *
  19575. * @type {boolean}
  19576. * @default false
  19577. */
  19578. this.stencil = false;
  19579. /**
  19580. * Whether the stencil attachment should be cleared or not.
  19581. *
  19582. * @type {boolean}
  19583. * @default true
  19584. */
  19585. this.clearStencil = true;
  19586. /**
  19587. * The clear stencil value.
  19588. *
  19589. * @type {number}
  19590. * @default 1
  19591. */
  19592. this.clearStencilValue = 1;
  19593. /**
  19594. * By default the viewport encloses the entire framebuffer If a smaller
  19595. * viewport is manually defined, this property is to `true` by the renderer.
  19596. *
  19597. * @type {boolean}
  19598. * @default false
  19599. */
  19600. this.viewport = false;
  19601. /**
  19602. * The viewport value. This value is in physical pixels meaning it incorporates
  19603. * the renderer's pixel ratio. The viewport property of render targets or
  19604. * the renderer is in logical pixels.
  19605. *
  19606. * @type {Vector4}
  19607. */
  19608. this.viewportValue = new Vector4();
  19609. /**
  19610. * When the scissor test is active and scissor rectangle smaller than the
  19611. * framebuffers dimensions, this property is to `true` by the renderer.
  19612. *
  19613. * @type {boolean}
  19614. * @default false
  19615. */
  19616. this.scissor = false;
  19617. /**
  19618. * The scissor rectangle.
  19619. *
  19620. * @type {Vector4}
  19621. */
  19622. this.scissorValue = new Vector4();
  19623. /**
  19624. * The active render target.
  19625. *
  19626. * @type {?RenderTarget}
  19627. * @default null
  19628. */
  19629. this.renderTarget = null;
  19630. /**
  19631. * The textures of the active render target.
  19632. * `null` when no render target is set.
  19633. *
  19634. * @type {?Array<Texture>}
  19635. * @default null
  19636. */
  19637. this.textures = null;
  19638. /**
  19639. * The depth texture of the active render target.
  19640. * `null` when no render target is set.
  19641. *
  19642. * @type {?DepthTexture}
  19643. * @default null
  19644. */
  19645. this.depthTexture = null;
  19646. /**
  19647. * The active cube face.
  19648. *
  19649. * @type {number}
  19650. * @default 0
  19651. */
  19652. this.activeCubeFace = 0;
  19653. /**
  19654. * The active mipmap level.
  19655. *
  19656. * @type {number}
  19657. * @default 0
  19658. */
  19659. this.activeMipmapLevel = 0;
  19660. /**
  19661. * The number of MSAA samples. This value is always `1` when
  19662. * MSAA isn't used.
  19663. *
  19664. * @type {number}
  19665. * @default 1
  19666. */
  19667. this.sampleCount = 1;
  19668. /**
  19669. * The active render target's width in physical pixels.
  19670. *
  19671. * @type {number}
  19672. * @default 0
  19673. */
  19674. this.width = 0;
  19675. /**
  19676. * The active render target's height in physical pixels.
  19677. *
  19678. * @type {number}
  19679. * @default 0
  19680. */
  19681. this.height = 0;
  19682. /**
  19683. * The occlusion query count.
  19684. *
  19685. * @type {number}
  19686. * @default 0
  19687. */
  19688. this.occlusionQueryCount = 0;
  19689. /**
  19690. * The current clipping context.
  19691. *
  19692. * @type {?ClippingContext}
  19693. * @default null
  19694. */
  19695. this.clippingContext = null;
  19696. /**
  19697. * This flag can be used for type testing.
  19698. *
  19699. * @type {boolean}
  19700. * @readonly
  19701. * @default true
  19702. */
  19703. this.isRenderContext = true;
  19704. }
  19705. /**
  19706. * Returns the cache key of this render context.
  19707. *
  19708. * @return {number} The cache key.
  19709. */
  19710. getCacheKey() {
  19711. return getCacheKey( this );
  19712. }
  19713. }
  19714. /**
  19715. * Computes a cache key for the given render context. This key
  19716. * should identify the render target state so it is possible to
  19717. * configure the correct attachments in the respective backend.
  19718. *
  19719. * @param {RenderContext} renderContext - The render context.
  19720. * @return {number} The cache key.
  19721. */
  19722. function getCacheKey( renderContext ) {
  19723. const { textures, activeCubeFace } = renderContext;
  19724. const values = [ activeCubeFace ];
  19725. for ( const texture of textures ) {
  19726. values.push( texture.id );
  19727. }
  19728. return hashArray( values );
  19729. }
  19730. const _chainKeys$3 = [];
  19731. const _defaultScene = /*@__PURE__*/ new Scene();
  19732. const _defaultCamera = /*@__PURE__*/ new Camera();
  19733. /**
  19734. * This module manages the render contexts of the renderer.
  19735. *
  19736. * @private
  19737. */
  19738. class RenderContexts {
  19739. /**
  19740. * Constructs a new render context management component.
  19741. */
  19742. constructor() {
  19743. /**
  19744. * A dictionary that manages render contexts in chain maps
  19745. * for each attachment state.
  19746. *
  19747. * @type {Object<string,ChainMap>}
  19748. */
  19749. this.chainMaps = {};
  19750. }
  19751. /**
  19752. * Returns a render context for the given scene, camera and render target.
  19753. *
  19754. * @param {Scene} scene - The scene.
  19755. * @param {Camera} camera - The camera that is used to render the scene.
  19756. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  19757. * @return {RenderContext} The render context.
  19758. */
  19759. get( scene, camera, renderTarget = null ) {
  19760. _chainKeys$3[ 0 ] = scene;
  19761. _chainKeys$3[ 1 ] = camera;
  19762. let attachmentState;
  19763. if ( renderTarget === null ) {
  19764. attachmentState = 'default';
  19765. } else {
  19766. const format = renderTarget.texture.format;
  19767. const count = renderTarget.textures.length;
  19768. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  19769. }
  19770. const chainMap = this._getChainMap( attachmentState );
  19771. let renderState = chainMap.get( _chainKeys$3 );
  19772. if ( renderState === undefined ) {
  19773. renderState = new RenderContext();
  19774. chainMap.set( _chainKeys$3, renderState );
  19775. }
  19776. _chainKeys$3.length = 0;
  19777. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  19778. return renderState;
  19779. }
  19780. /**
  19781. * Returns a render context intended for clear operations.
  19782. *
  19783. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  19784. * @return {RenderContext} The render context.
  19785. */
  19786. getForClear( renderTarget = null ) {
  19787. return this.get( _defaultScene, _defaultCamera, renderTarget );
  19788. }
  19789. /**
  19790. * Returns a chain map for the given attachment state.
  19791. *
  19792. * @private
  19793. * @param {string} attachmentState - The attachment state.
  19794. * @return {ChainMap} The chain map.
  19795. */
  19796. _getChainMap( attachmentState ) {
  19797. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  19798. }
  19799. /**
  19800. * Frees internal resources.
  19801. */
  19802. dispose() {
  19803. this.chainMaps = {};
  19804. }
  19805. }
  19806. const _size$3 = /*@__PURE__*/ new Vector3();
  19807. /**
  19808. * This module manages the textures of the renderer.
  19809. *
  19810. * @private
  19811. * @augments DataMap
  19812. */
  19813. class Textures extends DataMap {
  19814. /**
  19815. * Constructs a new texture management component.
  19816. *
  19817. * @param {Renderer} renderer - The renderer.
  19818. * @param {Backend} backend - The renderer's backend.
  19819. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19820. */
  19821. constructor( renderer, backend, info ) {
  19822. super();
  19823. /**
  19824. * The renderer.
  19825. *
  19826. * @type {Renderer}
  19827. */
  19828. this.renderer = renderer;
  19829. /**
  19830. * The backend.
  19831. *
  19832. * @type {Backend}
  19833. */
  19834. this.backend = backend;
  19835. /**
  19836. * Renderer component for managing metrics and monitoring data.
  19837. *
  19838. * @type {Info}
  19839. */
  19840. this.info = info;
  19841. }
  19842. /**
  19843. * Updates the given render target. Based on the given render target configuration,
  19844. * it updates the texture states representing the attachments of the framebuffer.
  19845. *
  19846. * @param {RenderTarget} renderTarget - The render target to update.
  19847. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  19848. */
  19849. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  19850. const renderTargetData = this.get( renderTarget );
  19851. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  19852. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  19853. const textures = renderTarget.textures;
  19854. const size = this.getSize( textures[ 0 ] );
  19855. const mipWidth = size.width >> activeMipmapLevel;
  19856. const mipHeight = size.height >> activeMipmapLevel;
  19857. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  19858. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  19859. let textureNeedsUpdate = false;
  19860. if ( depthTexture === undefined && useDepthTexture ) {
  19861. depthTexture = new DepthTexture();
  19862. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  19863. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  19864. depthTexture.image.width = mipWidth;
  19865. depthTexture.image.height = mipHeight;
  19866. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  19867. }
  19868. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  19869. textureNeedsUpdate = true;
  19870. if ( depthTexture ) {
  19871. depthTexture.needsUpdate = true;
  19872. depthTexture.image.width = mipWidth;
  19873. depthTexture.image.height = mipHeight;
  19874. }
  19875. }
  19876. renderTargetData.width = size.width;
  19877. renderTargetData.height = size.height;
  19878. renderTargetData.textures = textures;
  19879. renderTargetData.depthTexture = depthTexture || null;
  19880. renderTargetData.depth = renderTarget.depthBuffer;
  19881. renderTargetData.stencil = renderTarget.stencilBuffer;
  19882. renderTargetData.renderTarget = renderTarget;
  19883. if ( renderTargetData.sampleCount !== sampleCount ) {
  19884. textureNeedsUpdate = true;
  19885. if ( depthTexture ) {
  19886. depthTexture.needsUpdate = true;
  19887. }
  19888. renderTargetData.sampleCount = sampleCount;
  19889. }
  19890. //
  19891. const options = { sampleCount };
  19892. // XR render targets require no texture updates
  19893. if ( renderTarget.isXRRenderTarget !== true ) {
  19894. for ( let i = 0; i < textures.length; i ++ ) {
  19895. const texture = textures[ i ];
  19896. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  19897. this.updateTexture( texture, options );
  19898. }
  19899. if ( depthTexture ) {
  19900. this.updateTexture( depthTexture, options );
  19901. }
  19902. }
  19903. // dispose handler
  19904. if ( renderTargetData.initialized !== true ) {
  19905. renderTargetData.initialized = true;
  19906. // dispose
  19907. const onDispose = () => {
  19908. renderTarget.removeEventListener( 'dispose', onDispose );
  19909. for ( let i = 0; i < textures.length; i ++ ) {
  19910. this._destroyTexture( textures[ i ] );
  19911. }
  19912. if ( depthTexture ) {
  19913. this._destroyTexture( depthTexture );
  19914. }
  19915. this.delete( renderTarget );
  19916. };
  19917. renderTarget.addEventListener( 'dispose', onDispose );
  19918. }
  19919. }
  19920. /**
  19921. * Updates the given texture. Depending on the texture state, this method
  19922. * triggers the upload of texture data to the GPU memory. If the texture data are
  19923. * not yet ready for the upload, it uses default texture data for as a placeholder.
  19924. *
  19925. * @param {Texture} texture - The texture to update.
  19926. * @param {Object} [options={}] - The options.
  19927. */
  19928. updateTexture( texture, options = {} ) {
  19929. const textureData = this.get( texture );
  19930. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  19931. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  19932. const backend = this.backend;
  19933. if ( isRenderTarget && textureData.initialized === true ) {
  19934. // it's an update
  19935. backend.destroySampler( texture );
  19936. backend.destroyTexture( texture );
  19937. }
  19938. //
  19939. if ( texture.isFramebufferTexture ) {
  19940. const renderTarget = this.renderer.getRenderTarget();
  19941. if ( renderTarget ) {
  19942. texture.type = renderTarget.texture.type;
  19943. } else {
  19944. texture.type = UnsignedByteType;
  19945. }
  19946. }
  19947. //
  19948. const { width, height, depth } = this.getSize( texture );
  19949. options.width = width;
  19950. options.height = height;
  19951. options.depth = depth;
  19952. options.needsMipmaps = this.needsMipmaps( texture );
  19953. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  19954. //
  19955. if ( isRenderTarget || texture.isStorageTexture === true ) {
  19956. backend.createSampler( texture );
  19957. backend.createTexture( texture, options );
  19958. textureData.generation = texture.version;
  19959. } else {
  19960. const needsCreate = textureData.initialized !== true;
  19961. if ( needsCreate ) backend.createSampler( texture );
  19962. if ( texture.version > 0 ) {
  19963. const image = texture.image;
  19964. if ( image === undefined ) {
  19965. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  19966. } else if ( image.complete === false ) {
  19967. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  19968. } else {
  19969. if ( texture.images ) {
  19970. const images = [];
  19971. for ( const image of texture.images ) {
  19972. images.push( image );
  19973. }
  19974. options.images = images;
  19975. } else {
  19976. options.image = image;
  19977. }
  19978. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  19979. backend.createTexture( texture, options );
  19980. textureData.isDefaultTexture = false;
  19981. textureData.generation = texture.version;
  19982. }
  19983. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  19984. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  19985. }
  19986. } else {
  19987. // async update
  19988. backend.createDefaultTexture( texture );
  19989. textureData.isDefaultTexture = true;
  19990. textureData.generation = texture.version;
  19991. }
  19992. }
  19993. // dispose handler
  19994. if ( textureData.initialized !== true ) {
  19995. textureData.initialized = true;
  19996. textureData.generation = texture.version;
  19997. //
  19998. this.info.memory.textures ++;
  19999. // dispose
  20000. const onDispose = () => {
  20001. texture.removeEventListener( 'dispose', onDispose );
  20002. this._destroyTexture( texture );
  20003. this.info.memory.textures --;
  20004. };
  20005. texture.addEventListener( 'dispose', onDispose );
  20006. }
  20007. //
  20008. textureData.version = texture.version;
  20009. }
  20010. /**
  20011. * Computes the size of the given texture and writes the result
  20012. * into the target vector. This vector is also returned by the
  20013. * method.
  20014. *
  20015. * If no texture data are available for the compute yet, the method
  20016. * returns default size values.
  20017. *
  20018. * @param {Texture} texture - The texture to compute the size for.
  20019. * @param {Vector3} target - The target vector.
  20020. * @return {Vector3} The target vector.
  20021. */
  20022. getSize( texture, target = _size$3 ) {
  20023. let image = texture.images ? texture.images[ 0 ] : texture.image;
  20024. if ( image ) {
  20025. if ( image.image !== undefined ) image = image.image;
  20026. target.width = image.width || 1;
  20027. target.height = image.height || 1;
  20028. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  20029. } else {
  20030. target.width = target.height = target.depth = 1;
  20031. }
  20032. return target;
  20033. }
  20034. /**
  20035. * Computes the number of mipmap levels for the given texture.
  20036. *
  20037. * @param {Texture} texture - The texture.
  20038. * @param {number} width - The texture's width.
  20039. * @param {number} height - The texture's height.
  20040. * @return {number} The number of mipmap levels.
  20041. */
  20042. getMipLevels( texture, width, height ) {
  20043. let mipLevelCount;
  20044. if ( texture.isCompressedTexture ) {
  20045. if ( texture.mipmaps ) {
  20046. mipLevelCount = texture.mipmaps.length;
  20047. } else {
  20048. mipLevelCount = 1;
  20049. }
  20050. } else {
  20051. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  20052. }
  20053. return mipLevelCount;
  20054. }
  20055. /**
  20056. * Returns `true` if the given texture requires mipmaps.
  20057. *
  20058. * @param {Texture} texture - The texture.
  20059. * @return {boolean} Whether mipmaps are required or not.
  20060. */
  20061. needsMipmaps( texture ) {
  20062. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  20063. }
  20064. /**
  20065. * Returns `true` if the given texture is an environment map.
  20066. *
  20067. * @param {Texture} texture - The texture.
  20068. * @return {boolean} Whether the given texture is an environment map or not.
  20069. */
  20070. isEnvironmentTexture( texture ) {
  20071. const mapping = texture.mapping;
  20072. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  20073. }
  20074. /**
  20075. * Frees internal resource when the given texture isn't
  20076. * required anymore.
  20077. *
  20078. * @param {Texture} texture - The texture to destroy.
  20079. */
  20080. _destroyTexture( texture ) {
  20081. this.backend.destroySampler( texture );
  20082. this.backend.destroyTexture( texture );
  20083. this.delete( texture );
  20084. }
  20085. }
  20086. /**
  20087. * A four-component version of {@link Color} which is internally
  20088. * used by the renderer to represents clear color with alpha as
  20089. * one object.
  20090. *
  20091. * @private
  20092. * @augments Color
  20093. */
  20094. class Color4 extends Color {
  20095. /**
  20096. * Constructs a new four-component color.
  20097. * You can also pass a single THREE.Color, hex or
  20098. * string argument to this constructor.
  20099. *
  20100. * @param {number|string} [r=1] - The red value.
  20101. * @param {number} [g=1] - The green value.
  20102. * @param {number} [b=1] - The blue value.
  20103. * @param {number} [a=1] - The alpha value.
  20104. */
  20105. constructor( r, g, b, a = 1 ) {
  20106. super( r, g, b );
  20107. this.a = a;
  20108. }
  20109. /**
  20110. * Overwrites the default to honor alpha.
  20111. * You can also pass a single THREE.Color, hex or
  20112. * string argument to this method.
  20113. *
  20114. * @param {number|string|Color} r - The red value.
  20115. * @param {number} g - The green value.
  20116. * @param {number} b - The blue value.
  20117. * @param {number} [a=1] - The alpha value.
  20118. * @return {Color4} A reference to this object.
  20119. */
  20120. set( r, g, b, a = 1 ) {
  20121. this.a = a;
  20122. return super.set( r, g, b );
  20123. }
  20124. /**
  20125. * Overwrites the default to honor alpha.
  20126. *
  20127. * @param {Color4} color - The color to copy.
  20128. * @return {Color4} A reference to this object.
  20129. */
  20130. copy( color ) {
  20131. if ( color.a !== undefined ) this.a = color.a;
  20132. return super.copy( color );
  20133. }
  20134. /**
  20135. * Overwrites the default to honor alpha.
  20136. *
  20137. * @return {Color4} The cloned color.
  20138. */
  20139. clone() {
  20140. return new this.constructor( this.r, this.g, this.b, this.a );
  20141. }
  20142. }
  20143. /**
  20144. * Special version of {@link PropertyNode} which is used for parameters.
  20145. *
  20146. * @augments PropertyNode
  20147. */
  20148. class ParameterNode extends PropertyNode {
  20149. static get type() {
  20150. return 'ParameterNode';
  20151. }
  20152. /**
  20153. * Constructs a new parameter node.
  20154. *
  20155. * @param {string} nodeType - The type of the node.
  20156. * @param {?string} [name=null] - The name of the parameter in the shader.
  20157. */
  20158. constructor( nodeType, name = null ) {
  20159. super( nodeType, name );
  20160. /**
  20161. * This flag can be used for type testing.
  20162. *
  20163. * @type {boolean}
  20164. * @readonly
  20165. * @default true
  20166. */
  20167. this.isParameterNode = true;
  20168. }
  20169. getHash() {
  20170. return this.uuid;
  20171. }
  20172. generate() {
  20173. return this.name;
  20174. }
  20175. }
  20176. /**
  20177. * TSL function for creating a parameter node.
  20178. *
  20179. * @tsl
  20180. * @function
  20181. * @param {string} type - The type of the node.
  20182. * @param {?string} name - The name of the parameter in the shader.
  20183. * @returns {ParameterNode}
  20184. */
  20185. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  20186. /**
  20187. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  20188. * They are usually needed in cases like `If`, `Else`.
  20189. *
  20190. * @augments Node
  20191. */
  20192. class StackNode extends Node {
  20193. static get type() {
  20194. return 'StackNode';
  20195. }
  20196. /**
  20197. * Constructs a new stack node.
  20198. *
  20199. * @param {?StackNode} [parent=null] - The parent stack node.
  20200. */
  20201. constructor( parent = null ) {
  20202. super();
  20203. /**
  20204. * List of nodes.
  20205. *
  20206. * @type {Array<Node>}
  20207. */
  20208. this.nodes = [];
  20209. /**
  20210. * The output node.
  20211. *
  20212. * @type {?Node}
  20213. * @default null
  20214. */
  20215. this.outputNode = null;
  20216. /**
  20217. * The parent stack node.
  20218. *
  20219. * @type {?StackNode}
  20220. * @default null
  20221. */
  20222. this.parent = parent;
  20223. /**
  20224. * The current conditional node.
  20225. *
  20226. * @private
  20227. * @type {ConditionalNode}
  20228. * @default null
  20229. */
  20230. this._currentCond = null;
  20231. /**
  20232. * This flag can be used for type testing.
  20233. *
  20234. * @type {boolean}
  20235. * @readonly
  20236. * @default true
  20237. */
  20238. this.isStackNode = true;
  20239. }
  20240. getNodeType( builder ) {
  20241. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  20242. }
  20243. getMemberType( builder, name ) {
  20244. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  20245. }
  20246. /**
  20247. * Adds a node to this stack.
  20248. *
  20249. * @param {Node} node - The node to add.
  20250. * @return {StackNode} A reference to this stack node.
  20251. */
  20252. add( node ) {
  20253. this.nodes.push( node );
  20254. return this;
  20255. }
  20256. /**
  20257. * Represent an `if` statement in TSL.
  20258. *
  20259. * @param {Node} boolNode - Represents the condition.
  20260. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  20261. * @return {StackNode} A reference to this stack node.
  20262. */
  20263. If( boolNode, method ) {
  20264. const methodNode = new ShaderNode( method );
  20265. this._currentCond = select( boolNode, methodNode );
  20266. return this.add( this._currentCond );
  20267. }
  20268. /**
  20269. * Represent an `elseif` statement in TSL.
  20270. *
  20271. * @param {Node} boolNode - Represents the condition.
  20272. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  20273. * @return {StackNode} A reference to this stack node.
  20274. */
  20275. ElseIf( boolNode, method ) {
  20276. const methodNode = new ShaderNode( method );
  20277. const ifNode = select( boolNode, methodNode );
  20278. this._currentCond.elseNode = ifNode;
  20279. this._currentCond = ifNode;
  20280. return this;
  20281. }
  20282. /**
  20283. * Represent an `else` statement in TSL.
  20284. *
  20285. * @param {Function} method - TSL code which is executed in the `else` case.
  20286. * @return {StackNode} A reference to this stack node.
  20287. */
  20288. Else( method ) {
  20289. this._currentCond.elseNode = new ShaderNode( method );
  20290. return this;
  20291. }
  20292. build( builder, ...params ) {
  20293. const previousStack = getCurrentStack();
  20294. setCurrentStack( this );
  20295. for ( const node of this.nodes ) {
  20296. node.build( builder, 'void' );
  20297. }
  20298. setCurrentStack( previousStack );
  20299. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  20300. }
  20301. // Deprecated
  20302. /**
  20303. * @function
  20304. * @deprecated since r168. Use {@link StackNode#Else} instead.
  20305. *
  20306. * @param {...any} params
  20307. * @returns {StackNode}
  20308. */
  20309. else( ...params ) { // @deprecated, r168
  20310. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  20311. return this.Else( ...params );
  20312. }
  20313. /**
  20314. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  20315. *
  20316. * @param {...any} params
  20317. * @returns {StackNode}
  20318. */
  20319. elseif( ...params ) { // @deprecated, r168
  20320. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  20321. return this.ElseIf( ...params );
  20322. }
  20323. }
  20324. /**
  20325. * TSL function for creating a stack node.
  20326. *
  20327. * @tsl
  20328. * @function
  20329. * @param {?StackNode} [parent=null] - The parent stack node.
  20330. * @returns {StackNode}
  20331. */
  20332. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  20333. /**
  20334. * Generates a layout for struct members.
  20335. * This function takes an object representing struct members and returns an array of member layouts.
  20336. * Each member layout includes the member's name, type, and whether it is atomic.
  20337. *
  20338. * @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.
  20339. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  20340. */
  20341. function getMembersLayout( members ) {
  20342. return Object.entries( members ).map( ( [ name, value ] ) => {
  20343. if ( typeof value === 'string' ) {
  20344. return { name, type: value, atomic: false };
  20345. }
  20346. return { name, type: value.type, atomic: value.atomic || false };
  20347. } );
  20348. }
  20349. /**
  20350. * Represents a struct type node in the node-based system.
  20351. * This class is used to define and manage the layout and types of struct members.
  20352. * It extends the base Node class and provides methods to get the length of the struct,
  20353. * retrieve member types, and generate the struct type for a builder.
  20354. *
  20355. * @augments Node
  20356. */
  20357. class StructTypeNode extends Node {
  20358. static get type() {
  20359. return 'StructTypeNode';
  20360. }
  20361. /**
  20362. * Creates an instance of StructTypeNode.
  20363. *
  20364. * @param {Object} membersLayout - The layout of the members for the struct.
  20365. * @param {?string} [name=null] - The optional name of the struct.
  20366. */
  20367. constructor( membersLayout, name = null ) {
  20368. super( 'struct' );
  20369. /**
  20370. * The layout of the members for the struct
  20371. *
  20372. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  20373. */
  20374. this.membersLayout = getMembersLayout( membersLayout );
  20375. /**
  20376. * The name of the struct.
  20377. *
  20378. * @type {?string}
  20379. * @default null
  20380. */
  20381. this.name = name;
  20382. /**
  20383. * This flag can be used for type testing.
  20384. *
  20385. * @type {boolean}
  20386. * @readonly
  20387. * @default true
  20388. */
  20389. this.isStructLayoutNode = true;
  20390. }
  20391. /**
  20392. * Returns the length of the struct.
  20393. * The length is calculated by summing the lengths of the struct's members.
  20394. *
  20395. * @returns {number} The length of the struct.
  20396. */
  20397. getLength() {
  20398. let length = 0;
  20399. for ( const member of this.membersLayout ) {
  20400. length += getLengthFromType( member.type );
  20401. }
  20402. return length;
  20403. }
  20404. getMemberType( builder, name ) {
  20405. const member = this.membersLayout.find( m => m.name === name );
  20406. return member ? member.type : 'void';
  20407. }
  20408. getNodeType( builder ) {
  20409. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  20410. return structType.name;
  20411. }
  20412. setup( builder ) {
  20413. builder.addInclude( this );
  20414. }
  20415. generate( builder ) {
  20416. return this.getNodeType( builder );
  20417. }
  20418. }
  20419. /**
  20420. * StructNode allows to create custom structures with multiple members.
  20421. * This can also be used to define structures in attribute and uniform data.
  20422. *
  20423. * ```js
  20424. * // Define a custom struct
  20425. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  20426. *
  20427. * // Create a new instance of the struct
  20428. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  20429. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  20430. *
  20431. * // Access the struct members
  20432. * const min = bb.get( 'min' );
  20433. *
  20434. * // Assign a new value to a member
  20435. * min.assign( vec3() );
  20436. * ```
  20437. * @augments Node
  20438. */
  20439. class StructNode extends Node {
  20440. static get type() {
  20441. return 'StructNode';
  20442. }
  20443. constructor( structLayoutNode, values ) {
  20444. super( 'vec3' );
  20445. this.structLayoutNode = structLayoutNode;
  20446. this.values = values;
  20447. this.isStructNode = true;
  20448. }
  20449. getNodeType( builder ) {
  20450. return this.structLayoutNode.getNodeType( builder );
  20451. }
  20452. getMemberType( builder, name ) {
  20453. return this.structLayoutNode.getMemberType( builder, name );
  20454. }
  20455. generate( builder ) {
  20456. const nodeVar = builder.getVarFromNode( this );
  20457. const structType = nodeVar.type;
  20458. const propertyName = builder.getPropertyName( nodeVar );
  20459. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  20460. return nodeVar.name;
  20461. }
  20462. }
  20463. /**
  20464. * TSL function for creating a struct node.
  20465. *
  20466. * @tsl
  20467. * @function
  20468. * @param {Object} membersLayout - The layout of the struct members.
  20469. * @param {?string} [name=null] - The name of the struct.
  20470. * @returns {Function} The struct function.
  20471. */
  20472. const struct = ( membersLayout, name = null ) => {
  20473. const structLayout = new StructTypeNode( membersLayout, name );
  20474. const struct = ( ...params ) => {
  20475. let values = null;
  20476. if ( params.length > 0 ) {
  20477. if ( params[ 0 ].isNode ) {
  20478. values = {};
  20479. const names = Object.keys( membersLayout );
  20480. for ( let i = 0; i < params.length; i ++ ) {
  20481. values[ names[ i ] ] = params[ i ];
  20482. }
  20483. } else {
  20484. values = params[ 0 ];
  20485. }
  20486. }
  20487. return nodeObject( new StructNode( structLayout, values ) );
  20488. };
  20489. struct.layout = structLayout;
  20490. struct.isStruct = true;
  20491. return struct;
  20492. };
  20493. /**
  20494. * This node can be used to define multiple outputs in a shader programs.
  20495. *
  20496. * @augments Node
  20497. */
  20498. class OutputStructNode extends Node {
  20499. static get type() {
  20500. return 'OutputStructNode';
  20501. }
  20502. /**
  20503. * Constructs a new output struct node. The constructor can be invoked with an
  20504. * arbitrary number of nodes representing the members.
  20505. *
  20506. * @param {...Node} members - A parameter list of nodes.
  20507. */
  20508. constructor( ...members ) {
  20509. super();
  20510. /**
  20511. * An array of nodes which defines the output.
  20512. *
  20513. * @type {Array<Node>}
  20514. */
  20515. this.members = members;
  20516. /**
  20517. * This flag can be used for type testing.
  20518. *
  20519. * @type {boolean}
  20520. * @readonly
  20521. * @default true
  20522. */
  20523. this.isOutputStructNode = true;
  20524. }
  20525. getNodeType( builder ) {
  20526. const properties = builder.getNodeProperties( this );
  20527. if ( properties.membersLayout === undefined ) {
  20528. const members = this.members;
  20529. const membersLayout = [];
  20530. for ( let i = 0; i < members.length; i ++ ) {
  20531. const name = 'm' + i;
  20532. const type = members[ i ].getNodeType( builder );
  20533. membersLayout.push( { name, type, index: i } );
  20534. }
  20535. properties.membersLayout = membersLayout;
  20536. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  20537. }
  20538. return properties.structType.name;
  20539. }
  20540. generate( builder ) {
  20541. const propertyName = builder.getOutputStructName();
  20542. const members = this.members;
  20543. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  20544. for ( let i = 0; i < members.length; i ++ ) {
  20545. const snippet = members[ i ].build( builder );
  20546. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  20547. }
  20548. return propertyName;
  20549. }
  20550. }
  20551. /**
  20552. * TSL function for creating an output struct node.
  20553. *
  20554. * @tsl
  20555. * @function
  20556. * @param {...Node} members - A parameter list of nodes.
  20557. * @returns {OutputStructNode}
  20558. */
  20559. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  20560. /**
  20561. * Returns the MRT texture index for the given name.
  20562. *
  20563. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  20564. * @param {string} name - The name of the MRT texture which index is requested.
  20565. * @return {number} The texture index.
  20566. */
  20567. function getTextureIndex( textures, name ) {
  20568. for ( let i = 0; i < textures.length; i ++ ) {
  20569. if ( textures[ i ].name === name ) {
  20570. return i;
  20571. }
  20572. }
  20573. return -1;
  20574. }
  20575. /**
  20576. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  20577. * post-processing is shown below:
  20578. * ```js
  20579. * const mrtNode = mrt( {
  20580. * output: output,
  20581. * normal: normalView
  20582. * } ) );
  20583. * ```
  20584. * The MRT output is defined as a dictionary.
  20585. *
  20586. * @augments OutputStructNode
  20587. */
  20588. class MRTNode extends OutputStructNode {
  20589. static get type() {
  20590. return 'MRTNode';
  20591. }
  20592. /**
  20593. * Constructs a new output struct node.
  20594. *
  20595. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  20596. */
  20597. constructor( outputNodes ) {
  20598. super();
  20599. /**
  20600. * A dictionary representing the MRT outputs. The key
  20601. * is the name of the output, the value the node which produces
  20602. * the output result.
  20603. *
  20604. * @type {Object<string, Node>}
  20605. */
  20606. this.outputNodes = outputNodes;
  20607. /**
  20608. * This flag can be used for type testing.
  20609. *
  20610. * @type {boolean}
  20611. * @readonly
  20612. * @default true
  20613. */
  20614. this.isMRTNode = true;
  20615. }
  20616. /**
  20617. * Returns `true` if the MRT node has an output with the given name.
  20618. *
  20619. * @param {string} name - The name of the output.
  20620. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  20621. */
  20622. has( name ) {
  20623. return this.outputNodes[ name ] !== undefined;
  20624. }
  20625. /**
  20626. * Returns the output node for the given name.
  20627. *
  20628. * @param {string} name - The name of the output.
  20629. * @return {Node} The output node.
  20630. */
  20631. get( name ) {
  20632. return this.outputNodes[ name ];
  20633. }
  20634. /**
  20635. * Merges the outputs of the given MRT node with the outputs of this node.
  20636. *
  20637. * @param {MRTNode} mrtNode - The MRT to merge.
  20638. * @return {MRTNode} A new MRT node with merged outputs..
  20639. */
  20640. merge( mrtNode ) {
  20641. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  20642. return mrt( outputs );
  20643. }
  20644. setup( builder ) {
  20645. const outputNodes = this.outputNodes;
  20646. const mrt = builder.renderer.getRenderTarget();
  20647. const members = [];
  20648. const textures = mrt.textures;
  20649. for ( const name in outputNodes ) {
  20650. const index = getTextureIndex( textures, name );
  20651. members[ index ] = vec4( outputNodes[ name ] );
  20652. }
  20653. this.members = members;
  20654. return super.setup( builder );
  20655. }
  20656. }
  20657. /**
  20658. * TSL function for creating a MRT node.
  20659. *
  20660. * @tsl
  20661. * @function
  20662. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  20663. * @returns {MRTNode}
  20664. */
  20665. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  20666. /**
  20667. * Generates a hash value in the range `[0, 1]` from the given seed.
  20668. *
  20669. * @tsl
  20670. * @function
  20671. * @param {Node<float>} seed - The seed.
  20672. * @return {Node<float>} The hash value.
  20673. */
  20674. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  20675. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  20676. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  20677. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  20678. const result = word.shiftRight( 22 ).bitXor( word );
  20679. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  20680. } );
  20681. /**
  20682. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20683. * The corners are mapped to `0` and the center to `1`.
  20684. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20685. *
  20686. * @tsl
  20687. * @function
  20688. * @param {Node<float>} x - The value to remap.
  20689. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  20690. * @return {Node<float>} The remapped value.
  20691. */
  20692. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  20693. /**
  20694. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20695. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  20696. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20697. *
  20698. * @tsl
  20699. * @function
  20700. * @param {Node<float>} x - The value to remap.
  20701. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  20702. * @return {Node<float>} The remapped value.
  20703. */
  20704. 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 ) );
  20705. /**
  20706. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  20707. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  20708. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20709. *
  20710. * @tsl
  20711. * @function
  20712. * @param {Node<float>} x - The value to remap.
  20713. * @param {Node<float>} a - First control parameter.
  20714. * @param {Node<float>} b - Second control parameter.
  20715. * @return {Node<float>} The remapped value.
  20716. */
  20717. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  20718. /**
  20719. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  20720. * Reference: {@link https://iquilezles.org/articles/functions/}.
  20721. *
  20722. * @tsl
  20723. * @function
  20724. * @param {Node<float>} x - The value to compute the sin for.
  20725. * @param {Node<float>} k - Controls the amount of bounces.
  20726. * @return {Node<float>} The result value.
  20727. */
  20728. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  20729. // https://github.com/cabbibo/glsl-tri-noise-3d
  20730. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  20731. return x.fract().sub( .5 ).abs();
  20732. } ).setLayout( {
  20733. name: 'tri',
  20734. type: 'float',
  20735. inputs: [
  20736. { name: 'x', type: 'float' }
  20737. ]
  20738. } );
  20739. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  20740. 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. ) ) ) ) );
  20741. } ).setLayout( {
  20742. name: 'tri3',
  20743. type: 'vec3',
  20744. inputs: [
  20745. { name: 'p', type: 'vec3' }
  20746. ]
  20747. } );
  20748. /**
  20749. * Generates a noise value from the given position, speed and time parameters.
  20750. *
  20751. * @tsl
  20752. * @function
  20753. * @param {Node<vec3>} position - The position.
  20754. * @param {Node<float>} speed - The speed.
  20755. * @param {Node<float>} time - The time.
  20756. * @return {Node<float>} The generated noise.
  20757. */
  20758. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  20759. const p = vec3( position ).toVar();
  20760. const z = float( 1.4 ).toVar();
  20761. const rz = float( 0.0 ).toVar();
  20762. const bp = vec3( p ).toVar();
  20763. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  20764. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  20765. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  20766. bp.mulAssign( 1.8 );
  20767. z.mulAssign( 1.5 );
  20768. p.mulAssign( 1.2 );
  20769. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  20770. rz.addAssign( t.div( z ) );
  20771. bp.addAssign( 0.14 );
  20772. } );
  20773. return rz;
  20774. } ).setLayout( {
  20775. name: 'triNoise3D',
  20776. type: 'float',
  20777. inputs: [
  20778. { name: 'position', type: 'vec3' },
  20779. { name: 'speed', type: 'float' },
  20780. { name: 'time', type: 'float' }
  20781. ]
  20782. } );
  20783. /**
  20784. * This class allows to define multiple overloaded versions
  20785. * of the same function. Depending on the parameters of the function
  20786. * call, the node picks the best-fit overloaded version.
  20787. *
  20788. * @augments Node
  20789. */
  20790. class FunctionOverloadingNode extends Node {
  20791. static get type() {
  20792. return 'FunctionOverloadingNode';
  20793. }
  20794. /**
  20795. * Constructs a new function overloading node.
  20796. *
  20797. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  20798. * @param {...Node} parametersNodes - A list of parameter nodes.
  20799. */
  20800. constructor( functionNodes = [], ...parametersNodes ) {
  20801. super();
  20802. /**
  20803. * Array of `Fn` function definitions.
  20804. *
  20805. * @type {Array<Function>}
  20806. */
  20807. this.functionNodes = functionNodes;
  20808. /**
  20809. * A list of parameter nodes.
  20810. *
  20811. * @type {Array<Node>}
  20812. */
  20813. this.parametersNodes = parametersNodes;
  20814. /**
  20815. * The selected overloaded function call.
  20816. *
  20817. * @private
  20818. * @type {ShaderCallNodeInternal}
  20819. */
  20820. this._candidateFnCall = null;
  20821. /**
  20822. * This node is marked as global.
  20823. *
  20824. * @type {boolean}
  20825. * @default true
  20826. */
  20827. this.global = true;
  20828. }
  20829. /**
  20830. * This method is overwritten since the node type is inferred from
  20831. * the function's return type.
  20832. *
  20833. * @param {NodeBuilder} builder - The current node builder.
  20834. * @return {string} The node type.
  20835. */
  20836. getNodeType() {
  20837. return this.functionNodes[ 0 ].shaderNode.layout.type;
  20838. }
  20839. setup( builder ) {
  20840. const params = this.parametersNodes;
  20841. let candidateFnCall = this._candidateFnCall;
  20842. if ( candidateFnCall === null ) {
  20843. let candidateFn = null;
  20844. let candidateScore = -1;
  20845. for ( const functionNode of this.functionNodes ) {
  20846. const shaderNode = functionNode.shaderNode;
  20847. const layout = shaderNode.layout;
  20848. if ( layout === null ) {
  20849. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  20850. }
  20851. const inputs = layout.inputs;
  20852. if ( params.length === inputs.length ) {
  20853. let score = 0;
  20854. for ( let i = 0; i < params.length; i ++ ) {
  20855. const param = params[ i ];
  20856. const input = inputs[ i ];
  20857. if ( param.getNodeType( builder ) === input.type ) {
  20858. score ++;
  20859. } else {
  20860. score = 0;
  20861. }
  20862. }
  20863. if ( score > candidateScore ) {
  20864. candidateFn = functionNode;
  20865. candidateScore = score;
  20866. }
  20867. }
  20868. }
  20869. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  20870. }
  20871. return candidateFnCall;
  20872. }
  20873. }
  20874. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  20875. /**
  20876. * TSL function for creating a function overloading node.
  20877. *
  20878. * @tsl
  20879. * @function
  20880. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  20881. * @returns {FunctionOverloadingNode}
  20882. */
  20883. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  20884. /**
  20885. * Represents the elapsed time in seconds.
  20886. *
  20887. * @tsl
  20888. * @type {UniformNode<float>}
  20889. */
  20890. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  20891. /**
  20892. * Represents the delta time in seconds.
  20893. *
  20894. * @tsl
  20895. * @type {UniformNode<float>}
  20896. */
  20897. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  20898. /**
  20899. * Represents the current frame ID.
  20900. *
  20901. * @tsl
  20902. * @type {UniformNode<uint>}
  20903. */
  20904. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  20905. // Deprecated
  20906. /**
  20907. * @tsl
  20908. * @function
  20909. * @deprecated since r170. Use {@link time} instead.
  20910. *
  20911. * @param {number} [timeScale=1] - The time scale.
  20912. * @returns {UniformNode<float>}
  20913. */
  20914. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  20915. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  20916. return time.mul( timeScale );
  20917. };
  20918. /**
  20919. * @tsl
  20920. * @function
  20921. * @deprecated since r170. Use {@link time} instead.
  20922. *
  20923. * @param {number} [timeScale=1] - The time scale.
  20924. * @returns {UniformNode<float>}
  20925. */
  20926. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  20927. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  20928. return time.mul( timeScale );
  20929. };
  20930. /**
  20931. * @tsl
  20932. * @function
  20933. * @deprecated since r170. Use {@link deltaTime} instead.
  20934. *
  20935. * @param {number} [timeScale=1] - The time scale.
  20936. * @returns {UniformNode<float>}
  20937. */
  20938. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  20939. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  20940. return deltaTime.mul( timeScale );
  20941. };
  20942. /**
  20943. * Generates a sine wave oscillation based on a timer.
  20944. *
  20945. * @tsl
  20946. * @function
  20947. * @param {Node<float>} t - The timer to generate the oscillation with.
  20948. * @return {Node<float>} The oscillation node.
  20949. */
  20950. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  20951. /**
  20952. * Generates a square wave oscillation based on a timer.
  20953. *
  20954. * @tsl
  20955. * @function
  20956. * @param {Node<float>} t - The timer to generate the oscillation with.
  20957. * @return {Node<float>} The oscillation node.
  20958. */
  20959. const oscSquare = ( t = time ) => t.fract().round();
  20960. /**
  20961. * Generates a triangle wave oscillation based on a timer.
  20962. *
  20963. * @tsl
  20964. * @function
  20965. * @param {Node<float>} t - The timer to generate the oscillation with.
  20966. * @return {Node<float>} The oscillation node.
  20967. */
  20968. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  20969. /**
  20970. * Generates a sawtooth wave oscillation based on a timer.
  20971. *
  20972. * @tsl
  20973. * @function
  20974. * @param {Node<float>} t - The timer to generate the oscillation with.
  20975. * @return {Node<float>} The oscillation node.
  20976. */
  20977. const oscSawtooth = ( t = time ) => t.fract();
  20978. /**
  20979. * Rotates the given uv coordinates around a center point
  20980. *
  20981. * @tsl
  20982. * @function
  20983. * @param {Node<vec2>} uv - The uv coordinates.
  20984. * @param {Node<float>} rotation - The rotation defined in radians.
  20985. * @param {Node<vec2>} center - The center of rotation
  20986. * @return {Node<vec2>} The rotated uv coordinates.
  20987. */
  20988. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  20989. return rotate( uv.sub( center ), rotation ).add( center );
  20990. } );
  20991. /**
  20992. * Applies a spherical warping effect to the given uv coordinates.
  20993. *
  20994. * @tsl
  20995. * @function
  20996. * @param {Node<vec2>} uv - The uv coordinates.
  20997. * @param {Node<float>} strength - The strength of the effect.
  20998. * @param {Node<vec2>} center - The center point
  20999. * @return {Node<vec2>} The updated uv coordinates.
  21000. */
  21001. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  21002. const delta = uv.sub( center );
  21003. const delta2 = delta.dot( delta );
  21004. const delta4 = delta2.mul( delta2 );
  21005. const deltaOffset = delta4.mul( strength );
  21006. return uv.add( delta.mul( deltaOffset ) );
  21007. } );
  21008. /**
  21009. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  21010. * oriented always towards the camera.
  21011. *
  21012. * ```js
  21013. * material.vertexNode = billboarding();
  21014. * ```
  21015. *
  21016. * @tsl
  21017. * @function
  21018. * @param {Object} config - The configuration object.
  21019. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  21020. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  21021. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  21022. * @return {Node<vec3>} The updated vertex position in clip space.
  21023. */
  21024. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  21025. let worldMatrix;
  21026. if ( position !== null ) {
  21027. worldMatrix = modelWorldMatrix.toVar();
  21028. worldMatrix[ 3 ][ 0 ] = position.x;
  21029. worldMatrix[ 3 ][ 1 ] = position.y;
  21030. worldMatrix[ 3 ][ 2 ] = position.z;
  21031. } else {
  21032. worldMatrix = modelWorldMatrix;
  21033. }
  21034. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  21035. if ( defined( horizontal ) ) {
  21036. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  21037. modelViewMatrix[ 0 ][ 1 ] = 0;
  21038. modelViewMatrix[ 0 ][ 2 ] = 0;
  21039. }
  21040. if ( defined( vertical ) ) {
  21041. modelViewMatrix[ 1 ][ 0 ] = 0;
  21042. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  21043. modelViewMatrix[ 1 ][ 2 ] = 0;
  21044. }
  21045. modelViewMatrix[ 2 ][ 0 ] = 0;
  21046. modelViewMatrix[ 2 ][ 1 ] = 0;
  21047. modelViewMatrix[ 2 ][ 2 ] = 1;
  21048. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21049. } );
  21050. /**
  21051. * A special version of a screen uv function that involves a depth comparison
  21052. * when computing the final uvs. The function mitigates visual errors when
  21053. * using viewport texture nodes for refraction purposes. Without this function
  21054. * objects in front of a refractive surface might appear on the refractive surface
  21055. * which is incorrect.
  21056. *
  21057. * @tsl
  21058. * @function
  21059. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  21060. * @return {Node<vec2>} The update uv coordinates.
  21061. */
  21062. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  21063. const depth = linearDepth();
  21064. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  21065. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  21066. return finalUV;
  21067. } );
  21068. /**
  21069. * Can be used to compute texture coordinates for animated sprite sheets.
  21070. *
  21071. * ```js
  21072. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  21073. *
  21074. * material.colorNode = texture( spriteSheet, uvNode );
  21075. * ```
  21076. *
  21077. * @augments Node
  21078. */
  21079. class SpriteSheetUVNode extends Node {
  21080. static get type() {
  21081. return 'SpriteSheetUVNode';
  21082. }
  21083. /**
  21084. * Constructs a new sprite sheet uv node.
  21085. *
  21086. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  21087. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  21088. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  21089. */
  21090. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  21091. super( 'vec2' );
  21092. /**
  21093. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  21094. *
  21095. * @type {Node<vec2>}
  21096. */
  21097. this.countNode = countNode;
  21098. /**
  21099. * The uv node.
  21100. *
  21101. * @type {Node<vec2>}
  21102. */
  21103. this.uvNode = uvNode;
  21104. /**
  21105. * The node that defines the current frame/sprite.
  21106. *
  21107. * @type {Node<float>}
  21108. */
  21109. this.frameNode = frameNode;
  21110. }
  21111. setup() {
  21112. const { frameNode, uvNode, countNode } = this;
  21113. const { width, height } = countNode;
  21114. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  21115. const column = frameNum.mod( width );
  21116. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  21117. const scale = countNode.reciprocal();
  21118. const uvFrameOffset = vec2( column, row );
  21119. return uvNode.add( uvFrameOffset ).mul( scale );
  21120. }
  21121. }
  21122. /**
  21123. * TSL function for creating a sprite sheet uv node.
  21124. *
  21125. * @tsl
  21126. * @function
  21127. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  21128. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  21129. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  21130. * @returns {SpriteSheetUVNode}
  21131. */
  21132. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  21133. /**
  21134. * Can be used for triplanar texture mapping.
  21135. *
  21136. * ```js
  21137. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  21138. * ```
  21139. *
  21140. * @augments Node
  21141. */
  21142. class TriplanarTexturesNode extends Node {
  21143. static get type() {
  21144. return 'TriplanarTexturesNode';
  21145. }
  21146. /**
  21147. * Constructs a new triplanar textures node.
  21148. *
  21149. * @param {Node} textureXNode - First texture node.
  21150. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  21151. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  21152. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  21153. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  21154. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  21155. */
  21156. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  21157. super( 'vec4' );
  21158. /**
  21159. * First texture node.
  21160. *
  21161. * @type {Node}
  21162. */
  21163. this.textureXNode = textureXNode;
  21164. /**
  21165. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  21166. *
  21167. * @type {?Node}
  21168. * @default null
  21169. */
  21170. this.textureYNode = textureYNode;
  21171. /**
  21172. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  21173. *
  21174. * @type {?Node}
  21175. * @default null
  21176. */
  21177. this.textureZNode = textureZNode;
  21178. /**
  21179. * The scale node.
  21180. *
  21181. * @type {Node<float>}
  21182. * @default float(1)
  21183. */
  21184. this.scaleNode = scaleNode;
  21185. /**
  21186. * Vertex positions in local space.
  21187. *
  21188. * @type {Node<vec3>}
  21189. * @default positionLocal
  21190. */
  21191. this.positionNode = positionNode;
  21192. /**
  21193. * Normals in local space.
  21194. *
  21195. * @type {Node<vec3>}
  21196. * @default normalLocal
  21197. */
  21198. this.normalNode = normalNode;
  21199. }
  21200. setup() {
  21201. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  21202. // Ref: https://github.com/keijiro/StandardTriplanar
  21203. // Blending factor of triplanar mapping
  21204. let bf = normalNode.abs().normalize();
  21205. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  21206. // Triplanar mapping
  21207. const tx = positionNode.yz.mul( scaleNode );
  21208. const ty = positionNode.zx.mul( scaleNode );
  21209. const tz = positionNode.xy.mul( scaleNode );
  21210. // Base color
  21211. const textureX = textureXNode.value;
  21212. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  21213. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  21214. const cx = texture( textureX, tx ).mul( bf.x );
  21215. const cy = texture( textureY, ty ).mul( bf.y );
  21216. const cz = texture( textureZ, tz ).mul( bf.z );
  21217. return add( cx, cy, cz );
  21218. }
  21219. }
  21220. /**
  21221. * TSL function for creating a triplanar textures node.
  21222. *
  21223. * @tsl
  21224. * @function
  21225. * @param {Node} textureXNode - First texture node.
  21226. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  21227. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  21228. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  21229. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  21230. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  21231. * @returns {TriplanarTexturesNode}
  21232. */
  21233. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  21234. /**
  21235. * TSL function for creating a triplanar textures node.
  21236. *
  21237. * @tsl
  21238. * @function
  21239. * @param {Node} textureXNode - First texture node.
  21240. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  21241. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  21242. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  21243. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  21244. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  21245. * @returns {TriplanarTexturesNode}
  21246. */
  21247. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  21248. const _reflectorPlane = new Plane();
  21249. const _normal = new Vector3();
  21250. const _reflectorWorldPosition = new Vector3();
  21251. const _cameraWorldPosition = new Vector3();
  21252. const _rotationMatrix = new Matrix4();
  21253. const _lookAtPosition = new Vector3( 0, 0, -1 );
  21254. const clipPlane = new Vector4();
  21255. const _view = new Vector3();
  21256. const _target = new Vector3();
  21257. const _q = new Vector4();
  21258. const _size$2 = new Vector2();
  21259. const _defaultRT = new RenderTarget();
  21260. const _defaultUV = screenUV.flipX();
  21261. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  21262. let _inReflector = false;
  21263. /**
  21264. * This node can be used to implement mirror-like flat reflective surfaces.
  21265. *
  21266. * ```js
  21267. * const groundReflector = reflector();
  21268. * material.colorNode = groundReflector;
  21269. *
  21270. * const plane = new Mesh( geometry, material );
  21271. * plane.add( groundReflector.target );
  21272. * ```
  21273. *
  21274. * @augments TextureNode
  21275. */
  21276. class ReflectorNode extends TextureNode {
  21277. static get type() {
  21278. return 'ReflectorNode';
  21279. }
  21280. /**
  21281. * Constructs a new reflector node.
  21282. *
  21283. * @param {Object} [parameters={}] - An object holding configuration parameters.
  21284. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  21285. * @param {number} [parameters.resolution=1] - The resolution scale.
  21286. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  21287. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  21288. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  21289. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  21290. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  21291. */
  21292. constructor( parameters = {} ) {
  21293. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  21294. /**
  21295. * A reference to the internal reflector base node which holds the actual implementation.
  21296. *
  21297. * @private
  21298. * @type {ReflectorBaseNode}
  21299. * @default ReflectorBaseNode
  21300. */
  21301. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  21302. /**
  21303. * A reference to the internal depth node.
  21304. *
  21305. * @private
  21306. * @type {?Node}
  21307. * @default null
  21308. */
  21309. this._depthNode = null;
  21310. this.setUpdateMatrix( false );
  21311. }
  21312. /**
  21313. * A reference to the internal reflector node.
  21314. *
  21315. * @type {ReflectorBaseNode}
  21316. */
  21317. get reflector() {
  21318. return this._reflectorBaseNode;
  21319. }
  21320. /**
  21321. * A reference to 3D object the reflector is linked to.
  21322. *
  21323. * @type {Object3D}
  21324. */
  21325. get target() {
  21326. return this._reflectorBaseNode.target;
  21327. }
  21328. /**
  21329. * Returns a node representing the mirror's depth. That can be used
  21330. * to implement more advanced reflection effects like distance attenuation.
  21331. *
  21332. * @return {Node} The depth node.
  21333. */
  21334. getDepthNode() {
  21335. if ( this._depthNode === null ) {
  21336. if ( this._reflectorBaseNode.depth !== true ) {
  21337. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  21338. }
  21339. this._depthNode = nodeObject( new ReflectorNode( {
  21340. defaultTexture: _defaultRT.depthTexture,
  21341. reflector: this._reflectorBaseNode
  21342. } ) );
  21343. }
  21344. return this._depthNode;
  21345. }
  21346. setup( builder ) {
  21347. // ignore if used in post-processing
  21348. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  21349. return super.setup( builder );
  21350. }
  21351. clone() {
  21352. const texture = new this.constructor( this.reflectorNode );
  21353. texture._reflectorBaseNode = this._reflectorBaseNode;
  21354. return texture;
  21355. }
  21356. }
  21357. /**
  21358. * Holds the actual implementation of the reflector.
  21359. *
  21360. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  21361. * in `ReflectorNode`, see #29619.
  21362. *
  21363. * @private
  21364. * @augments Node
  21365. */
  21366. class ReflectorBaseNode extends Node {
  21367. static get type() {
  21368. return 'ReflectorBaseNode';
  21369. }
  21370. /**
  21371. * Constructs a new reflector base node.
  21372. *
  21373. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  21374. * @param {Object} [parameters={}] - An object holding configuration parameters.
  21375. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  21376. * @param {number} [parameters.resolution=1] - The resolution scale.
  21377. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  21378. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  21379. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  21380. */
  21381. constructor( textureNode, parameters = {} ) {
  21382. super();
  21383. const {
  21384. target = new Object3D(),
  21385. resolution = 1,
  21386. generateMipmaps = false,
  21387. bounces = true,
  21388. depth = false
  21389. } = parameters;
  21390. /**
  21391. * Represents the rendered reflections as a texture node.
  21392. *
  21393. * @type {TextureNode}
  21394. */
  21395. this.textureNode = textureNode;
  21396. /**
  21397. * The 3D object the reflector is linked to.
  21398. *
  21399. * @type {Object3D}
  21400. * @default {new Object3D()}
  21401. */
  21402. this.target = target;
  21403. /**
  21404. * The resolution scale.
  21405. *
  21406. * @type {number}
  21407. * @default {1}
  21408. */
  21409. this.resolution = resolution;
  21410. /**
  21411. * Whether mipmaps should be generated or not.
  21412. *
  21413. * @type {boolean}
  21414. * @default {false}
  21415. */
  21416. this.generateMipmaps = generateMipmaps;
  21417. /**
  21418. * Whether reflectors can render other reflector nodes or not.
  21419. *
  21420. * @type {boolean}
  21421. * @default {true}
  21422. */
  21423. this.bounces = bounces;
  21424. /**
  21425. * Whether depth data should be generated or not.
  21426. *
  21427. * @type {boolean}
  21428. * @default {false}
  21429. */
  21430. this.depth = depth;
  21431. /**
  21432. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  21433. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  21434. *
  21435. * @type {string}
  21436. * @default 'render'
  21437. */
  21438. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  21439. /**
  21440. * Weak map for managing virtual cameras.
  21441. *
  21442. * @type {WeakMap<Camera, Camera>}
  21443. */
  21444. this.virtualCameras = new WeakMap();
  21445. /**
  21446. * Weak map for managing render targets.
  21447. *
  21448. * @type {WeakMap<Camera, RenderTarget>}
  21449. */
  21450. this.renderTargets = new WeakMap();
  21451. /**
  21452. * Force render even if reflector is facing away from camera.
  21453. *
  21454. * @type {boolean}
  21455. * @default {false}
  21456. */
  21457. this.forceUpdate = false;
  21458. }
  21459. /**
  21460. * Updates the resolution of the internal render target.
  21461. *
  21462. * @private
  21463. * @param {RenderTarget} renderTarget - The render target to resize.
  21464. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  21465. */
  21466. _updateResolution( renderTarget, renderer ) {
  21467. const resolution = this.resolution;
  21468. renderer.getDrawingBufferSize( _size$2 );
  21469. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  21470. }
  21471. setup( builder ) {
  21472. this._updateResolution( _defaultRT, builder.renderer );
  21473. return super.setup( builder );
  21474. }
  21475. /**
  21476. * Returns a virtual camera for the given camera. The virtual camera is used to
  21477. * render the scene from the reflector's view so correct reflections can be produced.
  21478. *
  21479. * @param {Camera} camera - The scene's camera.
  21480. * @return {Camera} The corresponding virtual camera.
  21481. */
  21482. getVirtualCamera( camera ) {
  21483. let virtualCamera = this.virtualCameras.get( camera );
  21484. if ( virtualCamera === undefined ) {
  21485. virtualCamera = camera.clone();
  21486. this.virtualCameras.set( camera, virtualCamera );
  21487. }
  21488. return virtualCamera;
  21489. }
  21490. /**
  21491. * Returns a render target for the given camera. The reflections are rendered
  21492. * into this render target.
  21493. *
  21494. * @param {Camera} camera - The scene's camera.
  21495. * @return {RenderTarget} The render target.
  21496. */
  21497. getRenderTarget( camera ) {
  21498. let renderTarget = this.renderTargets.get( camera );
  21499. if ( renderTarget === undefined ) {
  21500. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  21501. if ( this.generateMipmaps === true ) {
  21502. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  21503. renderTarget.texture.generateMipmaps = true;
  21504. }
  21505. if ( this.depth === true ) {
  21506. renderTarget.depthTexture = new DepthTexture();
  21507. }
  21508. this.renderTargets.set( camera, renderTarget );
  21509. }
  21510. return renderTarget;
  21511. }
  21512. updateBefore( frame ) {
  21513. if ( this.bounces === false && _inReflector ) return false;
  21514. _inReflector = true;
  21515. const { scene, camera, renderer, material } = frame;
  21516. const { target } = this;
  21517. const virtualCamera = this.getVirtualCamera( camera );
  21518. const renderTarget = this.getRenderTarget( virtualCamera );
  21519. renderer.getDrawingBufferSize( _size$2 );
  21520. this._updateResolution( renderTarget, renderer );
  21521. //
  21522. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  21523. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  21524. _rotationMatrix.extractRotation( target.matrixWorld );
  21525. _normal.set( 0, 0, 1 );
  21526. _normal.applyMatrix4( _rotationMatrix );
  21527. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  21528. // Avoid rendering when reflector is facing away unless forcing an update
  21529. const isFacingAway = _view.dot( _normal ) > 0;
  21530. if ( isFacingAway === true && this.forceUpdate === false ) return;
  21531. _view.reflect( _normal ).negate();
  21532. _view.add( _reflectorWorldPosition );
  21533. _rotationMatrix.extractRotation( camera.matrixWorld );
  21534. _lookAtPosition.set( 0, 0, -1 );
  21535. _lookAtPosition.applyMatrix4( _rotationMatrix );
  21536. _lookAtPosition.add( _cameraWorldPosition );
  21537. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  21538. _target.reflect( _normal ).negate();
  21539. _target.add( _reflectorWorldPosition );
  21540. //
  21541. virtualCamera.coordinateSystem = camera.coordinateSystem;
  21542. virtualCamera.position.copy( _view );
  21543. virtualCamera.up.set( 0, 1, 0 );
  21544. virtualCamera.up.applyMatrix4( _rotationMatrix );
  21545. virtualCamera.up.reflect( _normal );
  21546. virtualCamera.lookAt( _target );
  21547. virtualCamera.near = camera.near;
  21548. virtualCamera.far = camera.far;
  21549. virtualCamera.updateMatrixWorld();
  21550. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  21551. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  21552. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  21553. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  21554. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  21555. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  21556. const projectionMatrix = virtualCamera.projectionMatrix;
  21557. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  21558. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  21559. _q.z = -1;
  21560. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  21561. // Calculate the scaled plane vector
  21562. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  21563. const clipBias = 0;
  21564. // Replacing the third row of the projection matrix
  21565. projectionMatrix.elements[ 2 ] = clipPlane.x;
  21566. projectionMatrix.elements[ 6 ] = clipPlane.y;
  21567. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  21568. projectionMatrix.elements[ 14 ] = clipPlane.w;
  21569. //
  21570. this.textureNode.value = renderTarget.texture;
  21571. if ( this.depth === true ) {
  21572. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  21573. }
  21574. material.visible = false;
  21575. const currentRenderTarget = renderer.getRenderTarget();
  21576. const currentMRT = renderer.getMRT();
  21577. const currentAutoClear = renderer.autoClear;
  21578. renderer.setMRT( null );
  21579. renderer.setRenderTarget( renderTarget );
  21580. renderer.autoClear = true;
  21581. renderer.render( scene, virtualCamera );
  21582. renderer.setMRT( currentMRT );
  21583. renderer.setRenderTarget( currentRenderTarget );
  21584. renderer.autoClear = currentAutoClear;
  21585. material.visible = true;
  21586. _inReflector = false;
  21587. this.forceUpdate = false;
  21588. }
  21589. }
  21590. /**
  21591. * TSL function for creating a reflector node.
  21592. *
  21593. * @tsl
  21594. * @function
  21595. * @param {Object} [parameters={}] - An object holding configuration parameters.
  21596. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  21597. * @param {number} [parameters.resolution=1] - The resolution scale.
  21598. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  21599. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  21600. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  21601. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  21602. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  21603. * @returns {ReflectorNode}
  21604. */
  21605. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  21606. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  21607. /**
  21608. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  21609. *
  21610. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  21611. *
  21612. * @private
  21613. * @augments BufferGeometry
  21614. */
  21615. class QuadGeometry extends BufferGeometry {
  21616. /**
  21617. * Constructs a new quad geometry.
  21618. *
  21619. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  21620. */
  21621. constructor( flipY = false ) {
  21622. super();
  21623. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  21624. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  21625. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  21626. }
  21627. }
  21628. const _geometry = /*@__PURE__*/ new QuadGeometry();
  21629. /**
  21630. * This module is a helper for passes which need to render a full
  21631. * screen effect which is quite common in context of post processing.
  21632. *
  21633. * The intended usage is to reuse a single quad mesh for rendering
  21634. * subsequent passes by just reassigning the `material` reference.
  21635. *
  21636. * Note: This module can only be used with `WebGPURenderer`.
  21637. *
  21638. * @augments Mesh
  21639. */
  21640. class QuadMesh extends Mesh {
  21641. /**
  21642. * Constructs a new quad mesh.
  21643. *
  21644. * @param {?Material} [material=null] - The material to render the quad mesh with.
  21645. */
  21646. constructor( material = null ) {
  21647. super( _geometry, material );
  21648. /**
  21649. * The camera to render the quad mesh with.
  21650. *
  21651. * @type {OrthographicCamera}
  21652. * @readonly
  21653. */
  21654. this.camera = _camera;
  21655. /**
  21656. * This flag can be used for type testing.
  21657. *
  21658. * @type {boolean}
  21659. * @readonly
  21660. * @default true
  21661. */
  21662. this.isQuadMesh = true;
  21663. }
  21664. /**
  21665. * Async version of `render()`.
  21666. *
  21667. * @async
  21668. * @param {Renderer} renderer - The renderer.
  21669. * @return {Promise} A Promise that resolves when the render has been finished.
  21670. */
  21671. async renderAsync( renderer ) {
  21672. return renderer.renderAsync( this, _camera );
  21673. }
  21674. /**
  21675. * Renders the quad mesh
  21676. *
  21677. * @param {Renderer} renderer - The renderer.
  21678. */
  21679. render( renderer ) {
  21680. renderer.render( this, _camera );
  21681. }
  21682. }
  21683. const _size$1 = /*@__PURE__*/ new Vector2();
  21684. /**
  21685. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  21686. * This module is especially relevant in context of post processing where certain nodes require
  21687. * texture input for their effects. With the helper function `convertToTexture()` which is based
  21688. * on this module, the node system can automatically ensure texture input if required.
  21689. *
  21690. * @augments TextureNode
  21691. */
  21692. class RTTNode extends TextureNode {
  21693. static get type() {
  21694. return 'RTTNode';
  21695. }
  21696. /**
  21697. * Constructs a new RTT node.
  21698. *
  21699. * @param {Node} node - The node to render a texture with.
  21700. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21701. * @param {?number} [height=null] - The height of the internal render target.
  21702. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21703. */
  21704. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  21705. const renderTarget = new RenderTarget( width, height, options );
  21706. super( renderTarget.texture, uv() );
  21707. /**
  21708. * The node to render a texture with.
  21709. *
  21710. * @type {Node}
  21711. */
  21712. this.node = node;
  21713. /**
  21714. * The width of the internal render target.
  21715. * If not width is applied, the render target is automatically resized.
  21716. *
  21717. * @type {?number}
  21718. * @default null
  21719. */
  21720. this.width = width;
  21721. /**
  21722. * The height of the internal render target.
  21723. *
  21724. * @type {?number}
  21725. * @default null
  21726. */
  21727. this.height = height;
  21728. /**
  21729. * The pixel ratio
  21730. *
  21731. * @type {number}
  21732. * @default 1
  21733. */
  21734. this.pixelRatio = 1;
  21735. /**
  21736. * The render target
  21737. *
  21738. * @type {RenderTarget}
  21739. */
  21740. this.renderTarget = renderTarget;
  21741. /**
  21742. * Whether the texture requires an update or not.
  21743. *
  21744. * @type {boolean}
  21745. * @default true
  21746. */
  21747. this.textureNeedsUpdate = true;
  21748. /**
  21749. * Whether the texture should automatically be updated or not.
  21750. *
  21751. * @type {boolean}
  21752. * @default true
  21753. */
  21754. this.autoUpdate = true;
  21755. /**
  21756. * The node which is used with the quad mesh for RTT.
  21757. *
  21758. * @private
  21759. * @type {Node}
  21760. * @default null
  21761. */
  21762. this._rttNode = null;
  21763. /**
  21764. * The internal quad mesh for RTT.
  21765. *
  21766. * @private
  21767. * @type {QuadMesh}
  21768. */
  21769. this._quadMesh = new QuadMesh( new NodeMaterial() );
  21770. /**
  21771. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  21772. * the texture once per render in its {@link RTTNode#updateBefore} method.
  21773. *
  21774. * @type {string}
  21775. * @default 'render'
  21776. */
  21777. this.updateBeforeType = NodeUpdateType.RENDER;
  21778. }
  21779. /**
  21780. * Whether the internal render target should automatically be resized or not.
  21781. *
  21782. * @type {boolean}
  21783. * @readonly
  21784. * @default true
  21785. */
  21786. get autoSize() {
  21787. return this.width === null;
  21788. }
  21789. setup( builder ) {
  21790. this._rttNode = this.node.context( builder.getSharedContext() );
  21791. this._quadMesh.material.name = 'RTT';
  21792. this._quadMesh.material.needsUpdate = true;
  21793. return super.setup( builder );
  21794. }
  21795. /**
  21796. * Sets the size of the internal render target
  21797. *
  21798. * @param {number} width - The width to set.
  21799. * @param {number} height - The width to set.
  21800. */
  21801. setSize( width, height ) {
  21802. this.width = width;
  21803. this.height = height;
  21804. const effectiveWidth = width * this.pixelRatio;
  21805. const effectiveHeight = height * this.pixelRatio;
  21806. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  21807. this.textureNeedsUpdate = true;
  21808. }
  21809. /**
  21810. * Sets the pixel ratio. This will also resize the render target.
  21811. *
  21812. * @param {number} pixelRatio - The pixel ratio to set.
  21813. */
  21814. setPixelRatio( pixelRatio ) {
  21815. this.pixelRatio = pixelRatio;
  21816. this.setSize( this.width, this.height );
  21817. }
  21818. updateBefore( { renderer } ) {
  21819. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  21820. this.textureNeedsUpdate = false;
  21821. //
  21822. if ( this.autoSize === true ) {
  21823. this.pixelRatio = renderer.getPixelRatio();
  21824. const size = renderer.getSize( _size$1 );
  21825. this.setSize( size.width, size.height );
  21826. }
  21827. //
  21828. this._quadMesh.material.fragmentNode = this._rttNode;
  21829. //
  21830. const currentRenderTarget = renderer.getRenderTarget();
  21831. renderer.setRenderTarget( this.renderTarget );
  21832. this._quadMesh.render( renderer );
  21833. renderer.setRenderTarget( currentRenderTarget );
  21834. }
  21835. clone() {
  21836. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  21837. newNode.sampler = this.sampler;
  21838. newNode.referenceNode = this;
  21839. return newNode;
  21840. }
  21841. }
  21842. /**
  21843. * TSL function for creating a RTT node.
  21844. *
  21845. * @tsl
  21846. * @function
  21847. * @param {Node} node - The node to render a texture with.
  21848. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21849. * @param {?number} [height=null] - The height of the internal render target.
  21850. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21851. * @returns {RTTNode}
  21852. */
  21853. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  21854. /**
  21855. * TSL function for converting nodes to textures nodes.
  21856. *
  21857. * @tsl
  21858. * @function
  21859. * @param {Node} node - The node to render a texture with.
  21860. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  21861. * @param {?number} [height=null] - The height of the internal render target.
  21862. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  21863. * @returns {RTTNode}
  21864. */
  21865. const convertToTexture = ( node, ...params ) => {
  21866. if ( node.isTextureNode ) return node;
  21867. if ( node.isPassNode ) return node.getTextureNode();
  21868. return rtt( node, ...params );
  21869. };
  21870. /**
  21871. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  21872. * depth value and the camera's inverse projection matrix.
  21873. *
  21874. * @tsl
  21875. * @function
  21876. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  21877. * @param {Node<float>} depth - The fragment's depth value.
  21878. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  21879. * @return {Node<vec3>} The fragments position in view space.
  21880. */
  21881. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  21882. let clipSpacePosition;
  21883. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  21884. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  21885. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  21886. } else {
  21887. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  21888. }
  21889. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  21890. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  21891. } );
  21892. /**
  21893. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  21894. * and the camera's projection matrix
  21895. *
  21896. * @tsl
  21897. * @function
  21898. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  21899. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  21900. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  21901. */
  21902. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  21903. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  21904. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  21905. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  21906. } );
  21907. /**
  21908. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  21909. * target is available or if flat surface normals are required.
  21910. *
  21911. * @tsl
  21912. * @function
  21913. * @param {Node<vec2>} uv - The texture coordinate.
  21914. * @param {DepthTexture} depthTexture - The depth texture.
  21915. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  21916. * @return {Node<vec3>} The computed normal vector.
  21917. */
  21918. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  21919. const size = textureSize( textureLoad( depthTexture ) );
  21920. const p = ivec2( uv.mul( size ) ).toVar();
  21921. const c0 = textureLoad( depthTexture, p ).toVar();
  21922. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  21923. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  21924. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  21925. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  21926. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  21927. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  21928. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  21929. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  21930. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  21931. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  21932. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  21933. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  21934. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  21935. 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 ) ) );
  21936. 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 ) ) );
  21937. return normalize( cross( dpdx, dpdy ) );
  21938. } );
  21939. /**
  21940. * This special type of instanced buffer attribute is intended for compute shaders.
  21941. * In earlier three.js versions it was only possible to update attribute data
  21942. * on the CPU via JavaScript and then upload the data to the GPU. With the
  21943. * new material system and renderer it is now possible to use compute shaders
  21944. * to compute the data for an attribute more efficiently on the GPU.
  21945. *
  21946. * The idea is to create an instance of this class and provide it as an input
  21947. * to {@link StorageBufferNode}.
  21948. *
  21949. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  21950. *
  21951. * @augments InstancedBufferAttribute
  21952. */
  21953. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  21954. /**
  21955. * Constructs a new storage instanced buffer attribute.
  21956. *
  21957. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  21958. * The subsequent parameters are then obsolete.
  21959. * @param {number} itemSize - The item size.
  21960. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  21961. */
  21962. constructor( count, itemSize, typeClass = Float32Array ) {
  21963. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  21964. super( array, itemSize );
  21965. /**
  21966. * This flag can be used for type testing.
  21967. *
  21968. * @type {boolean}
  21969. * @readonly
  21970. * @default true
  21971. */
  21972. this.isStorageInstancedBufferAttribute = true;
  21973. }
  21974. }
  21975. /**
  21976. * This special type of buffer attribute is intended for compute shaders.
  21977. * In earlier three.js versions it was only possible to update attribute data
  21978. * on the CPU via JavaScript and then upload the data to the GPU. With the
  21979. * new material system and renderer it is now possible to use compute shaders
  21980. * to compute the data for an attribute more efficiently on the GPU.
  21981. *
  21982. * The idea is to create an instance of this class and provide it as an input
  21983. * to {@link StorageBufferNode}.
  21984. *
  21985. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  21986. *
  21987. * @augments BufferAttribute
  21988. */
  21989. class StorageBufferAttribute extends BufferAttribute {
  21990. /**
  21991. * Constructs a new storage buffer attribute.
  21992. *
  21993. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  21994. * The subsequent parameters are then obsolete.
  21995. * @param {number} itemSize - The item size.
  21996. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  21997. */
  21998. constructor( count, itemSize, typeClass = Float32Array ) {
  21999. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  22000. super( array, itemSize );
  22001. /**
  22002. * This flag can be used for type testing.
  22003. *
  22004. * @type {boolean}
  22005. * @readonly
  22006. * @default true
  22007. */
  22008. this.isStorageBufferAttribute = true;
  22009. }
  22010. }
  22011. /**
  22012. * This class enables element access on instances of {@link StorageBufferNode}.
  22013. * In most cases, it is indirectly used when accessing elements with the
  22014. * {@link StorageBufferNode#element} method.
  22015. *
  22016. * ```js
  22017. * const position = positionStorage.element( instanceIndex );
  22018. * ```
  22019. *
  22020. * @augments ArrayElementNode
  22021. */
  22022. class StorageArrayElementNode extends ArrayElementNode {
  22023. static get type() {
  22024. return 'StorageArrayElementNode';
  22025. }
  22026. /**
  22027. * Constructs storage buffer element node.
  22028. *
  22029. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  22030. * @param {Node} indexNode - The index node that defines the element access.
  22031. */
  22032. constructor( storageBufferNode, indexNode ) {
  22033. super( storageBufferNode, indexNode );
  22034. /**
  22035. * This flag can be used for type testing.
  22036. *
  22037. * @type {boolean}
  22038. * @readonly
  22039. * @default true
  22040. */
  22041. this.isStorageArrayElementNode = true;
  22042. }
  22043. /**
  22044. * The storage buffer node.
  22045. *
  22046. * @param {Node} value
  22047. * @type {StorageBufferNode}
  22048. */
  22049. set storageBufferNode( value ) {
  22050. this.node = value;
  22051. }
  22052. get storageBufferNode() {
  22053. return this.node;
  22054. }
  22055. getMemberType( builder, name ) {
  22056. const structTypeNode = this.storageBufferNode.structTypeNode;
  22057. if ( structTypeNode ) {
  22058. return structTypeNode.getMemberType( builder, name );
  22059. }
  22060. return 'void';
  22061. }
  22062. setup( builder ) {
  22063. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  22064. if ( this.node.isPBO === true ) {
  22065. builder.setupPBO( this.node );
  22066. }
  22067. }
  22068. return super.setup( builder );
  22069. }
  22070. generate( builder, output ) {
  22071. let snippet;
  22072. const isAssignContext = builder.context.assign;
  22073. //
  22074. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  22075. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  22076. snippet = builder.generatePBO( this );
  22077. } else {
  22078. snippet = this.node.build( builder );
  22079. }
  22080. } else {
  22081. snippet = super.generate( builder );
  22082. }
  22083. if ( isAssignContext !== true ) {
  22084. const type = this.getNodeType( builder );
  22085. snippet = builder.format( snippet, type, output );
  22086. }
  22087. return snippet;
  22088. }
  22089. }
  22090. /**
  22091. * TSL function for creating a storage element node.
  22092. *
  22093. * @tsl
  22094. * @function
  22095. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  22096. * @param {Node} indexNode - The index node that defines the element access.
  22097. * @returns {StorageArrayElementNode}
  22098. */
  22099. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  22100. /**
  22101. * This node is used in context of compute shaders and allows to define a
  22102. * storage buffer for data. A typical workflow is to create instances of
  22103. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  22104. * setup up a compute shader that writes into the buffers and then convert
  22105. * the storage buffers to attribute nodes for rendering.
  22106. *
  22107. * ```js
  22108. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  22109. *
  22110. * const computeInit = Fn( () => { // the compute shader
  22111. *
  22112. * const position = positionBuffer.element( instanceIndex );
  22113. *
  22114. * // compute position data
  22115. *
  22116. * position.x = 1;
  22117. * position.y = 1;
  22118. * position.z = 1;
  22119. *
  22120. * } )().compute( particleCount );
  22121. *
  22122. * const particleMaterial = new THREE.SpriteNodeMaterial();
  22123. * particleMaterial.positionNode = positionBuffer.toAttribute();
  22124. *
  22125. * renderer.computeAsync( computeInit );
  22126. *
  22127. * ```
  22128. *
  22129. * @augments BufferNode
  22130. */
  22131. class StorageBufferNode extends BufferNode {
  22132. static get type() {
  22133. return 'StorageBufferNode';
  22134. }
  22135. /**
  22136. * Constructs a new storage buffer node.
  22137. *
  22138. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  22139. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  22140. * @param {number} [bufferCount=0] - The buffer count.
  22141. */
  22142. constructor( value, bufferType = null, bufferCount = 0 ) {
  22143. let nodeType, structTypeNode = null;
  22144. if ( bufferType && bufferType.isStruct ) {
  22145. nodeType = 'struct';
  22146. structTypeNode = bufferType.layout;
  22147. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  22148. nodeType = getTypeFromLength( value.itemSize );
  22149. bufferCount = value.count;
  22150. } else {
  22151. nodeType = bufferType;
  22152. }
  22153. super( value, nodeType, bufferCount );
  22154. /**
  22155. * This flag can be used for type testing.
  22156. *
  22157. * @type {boolean}
  22158. * @readonly
  22159. * @default true
  22160. */
  22161. this.isStorageBufferNode = true;
  22162. /**
  22163. * The buffer struct type.
  22164. *
  22165. * @type {?StructTypeNode}
  22166. * @default null
  22167. */
  22168. this.structTypeNode = structTypeNode;
  22169. /**
  22170. * The access type of the texture node.
  22171. *
  22172. * @type {string}
  22173. * @default 'readWrite'
  22174. */
  22175. this.access = NodeAccess.READ_WRITE;
  22176. /**
  22177. * Whether the node is atomic or not.
  22178. *
  22179. * @type {boolean}
  22180. * @default false
  22181. */
  22182. this.isAtomic = false;
  22183. /**
  22184. * Whether the node represents a PBO or not.
  22185. * Only relevant for WebGL.
  22186. *
  22187. * @type {boolean}
  22188. * @default false
  22189. */
  22190. this.isPBO = false;
  22191. /**
  22192. * A reference to the internal buffer attribute node.
  22193. *
  22194. * @type {?BufferAttributeNode}
  22195. * @default null
  22196. */
  22197. this._attribute = null;
  22198. /**
  22199. * A reference to the internal varying node.
  22200. *
  22201. * @type {?VaryingNode}
  22202. * @default null
  22203. */
  22204. this._varying = null;
  22205. /**
  22206. * `StorageBufferNode` sets this property to `true` by default.
  22207. *
  22208. * @type {boolean}
  22209. * @default true
  22210. */
  22211. this.global = true;
  22212. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  22213. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  22214. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  22215. else value.isStorageBufferAttribute = true;
  22216. }
  22217. }
  22218. /**
  22219. * This method is overwritten since the buffer data might be shared
  22220. * and thus the hash should be shared as well.
  22221. *
  22222. * @param {NodeBuilder} builder - The current node builder.
  22223. * @return {string} The hash.
  22224. */
  22225. getHash( builder ) {
  22226. if ( this.bufferCount === 0 ) {
  22227. let bufferData = builder.globalCache.getData( this.value );
  22228. if ( bufferData === undefined ) {
  22229. bufferData = {
  22230. node: this
  22231. };
  22232. builder.globalCache.setData( this.value, bufferData );
  22233. }
  22234. return bufferData.node.uuid;
  22235. }
  22236. return this.uuid;
  22237. }
  22238. /**
  22239. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  22240. *
  22241. * @param {NodeBuilder} builder - The current node builder.
  22242. * @return {string} The input type.
  22243. */
  22244. getInputType( /*builder*/ ) {
  22245. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  22246. }
  22247. /**
  22248. * Enables element access with the given index node.
  22249. *
  22250. * @param {IndexNode} indexNode - The index node.
  22251. * @return {StorageArrayElementNode} A node representing the element access.
  22252. */
  22253. element( indexNode ) {
  22254. return storageElement( this, indexNode );
  22255. }
  22256. /**
  22257. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  22258. *
  22259. * @param {boolean} value - The value so set.
  22260. * @return {StorageBufferNode} A reference to this node.
  22261. */
  22262. setPBO( value ) {
  22263. this.isPBO = value;
  22264. return this;
  22265. }
  22266. /**
  22267. * Returns the `isPBO` value.
  22268. *
  22269. * @return {boolean} Whether the node represents a PBO or not.
  22270. */
  22271. getPBO() {
  22272. return this.isPBO;
  22273. }
  22274. /**
  22275. * Defines the node access.
  22276. *
  22277. * @param {string} value - The node access.
  22278. * @return {StorageBufferNode} A reference to this node.
  22279. */
  22280. setAccess( value ) {
  22281. this.access = value;
  22282. return this;
  22283. }
  22284. /**
  22285. * Convenience method for configuring a read-only node access.
  22286. *
  22287. * @return {StorageBufferNode} A reference to this node.
  22288. */
  22289. toReadOnly() {
  22290. return this.setAccess( NodeAccess.READ_ONLY );
  22291. }
  22292. /**
  22293. * Defines whether the node is atomic or not.
  22294. *
  22295. * @param {boolean} value - The atomic flag.
  22296. * @return {StorageBufferNode} A reference to this node.
  22297. */
  22298. setAtomic( value ) {
  22299. this.isAtomic = value;
  22300. return this;
  22301. }
  22302. /**
  22303. * Convenience method for making this node atomic.
  22304. *
  22305. * @return {StorageBufferNode} A reference to this node.
  22306. */
  22307. toAtomic() {
  22308. return this.setAtomic( true );
  22309. }
  22310. /**
  22311. * Returns attribute data for this storage buffer node.
  22312. *
  22313. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  22314. */
  22315. getAttributeData() {
  22316. if ( this._attribute === null ) {
  22317. this._attribute = bufferAttribute( this.value );
  22318. this._varying = varying( this._attribute );
  22319. }
  22320. return {
  22321. attribute: this._attribute,
  22322. varying: this._varying
  22323. };
  22324. }
  22325. /**
  22326. * This method is overwritten since the node type from the availability of storage buffers
  22327. * and the attribute data.
  22328. *
  22329. * @param {NodeBuilder} builder - The current node builder.
  22330. * @return {string} The node type.
  22331. */
  22332. getNodeType( builder ) {
  22333. if ( this.structTypeNode !== null ) {
  22334. return this.structTypeNode.getNodeType( builder );
  22335. }
  22336. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  22337. return super.getNodeType( builder );
  22338. }
  22339. const { attribute } = this.getAttributeData();
  22340. return attribute.getNodeType( builder );
  22341. }
  22342. /**
  22343. * Generates the code snippet of the storage buffer node.
  22344. *
  22345. * @param {NodeBuilder} builder - The current node builder.
  22346. * @return {string} The generated code snippet.
  22347. */
  22348. generate( builder ) {
  22349. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  22350. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  22351. return super.generate( builder );
  22352. }
  22353. const { attribute, varying } = this.getAttributeData();
  22354. const output = varying.build( builder );
  22355. builder.registerTransform( output, attribute );
  22356. return output;
  22357. }
  22358. }
  22359. /**
  22360. * TSL function for creating a storage buffer node.
  22361. *
  22362. * @tsl
  22363. * @function
  22364. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  22365. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  22366. * @param {number} [count=0] - The buffer count.
  22367. * @returns {StorageBufferNode}
  22368. */
  22369. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  22370. /**
  22371. * @tsl
  22372. * @function
  22373. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  22374. *
  22375. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  22376. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  22377. * @param {number} count - The buffer count.
  22378. * @returns {StorageBufferNode}
  22379. */
  22380. const storageObject = ( value, type, count ) => { // @deprecated, r171
  22381. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  22382. return storage( value, type, count ).setPBO( true );
  22383. };
  22384. /**
  22385. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  22386. *
  22387. * @tsl
  22388. * @function
  22389. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  22390. * @param {string|Struct} [type='float'] - The data type.
  22391. * @returns {StorageBufferNode}
  22392. */
  22393. const attributeArray = ( count, type = 'float' ) => {
  22394. let itemSize, typedArray;
  22395. if ( type.isStruct === true ) {
  22396. itemSize = type.layout.getLength();
  22397. typedArray = getTypedArrayFromType( 'float' );
  22398. } else {
  22399. itemSize = getLengthFromType( type );
  22400. typedArray = getTypedArrayFromType( type );
  22401. }
  22402. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  22403. const node = storage( buffer, type, count );
  22404. return node;
  22405. };
  22406. /**
  22407. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  22408. *
  22409. * @tsl
  22410. * @function
  22411. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  22412. * @param {string|Struct} [type='float'] - The data type.
  22413. * @returns {StorageBufferNode}
  22414. */
  22415. const instancedArray = ( count, type = 'float' ) => {
  22416. let itemSize, typedArray;
  22417. if ( type.isStruct === true ) {
  22418. itemSize = type.layout.getLength();
  22419. typedArray = getTypedArrayFromType( 'float' );
  22420. } else {
  22421. itemSize = getLengthFromType( type );
  22422. typedArray = getTypedArrayFromType( type );
  22423. }
  22424. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  22425. const node = storage( buffer, type, count );
  22426. return node;
  22427. };
  22428. /**
  22429. * An attribute node for representing vertex colors.
  22430. *
  22431. * @augments AttributeNode
  22432. */
  22433. class VertexColorNode extends AttributeNode {
  22434. static get type() {
  22435. return 'VertexColorNode';
  22436. }
  22437. /**
  22438. * Constructs a new vertex color node.
  22439. *
  22440. * @param {number} [index=0] - The attribute index.
  22441. */
  22442. constructor( index = 0 ) {
  22443. super( null, 'vec4' );
  22444. /**
  22445. * This flag can be used for type testing.
  22446. *
  22447. * @type {boolean}
  22448. * @readonly
  22449. * @default true
  22450. */
  22451. this.isVertexColorNode = true;
  22452. /**
  22453. * The attribute index to enable more than one sets of vertex colors.
  22454. *
  22455. * @type {number}
  22456. * @default 0
  22457. */
  22458. this.index = index;
  22459. }
  22460. /**
  22461. * Overwrites the default implementation by honoring the attribute index.
  22462. *
  22463. * @param {NodeBuilder} builder - The current node builder.
  22464. * @return {string} The attribute name.
  22465. */
  22466. getAttributeName( /*builder*/ ) {
  22467. const index = this.index;
  22468. return 'color' + ( index > 0 ? index : '' );
  22469. }
  22470. generate( builder ) {
  22471. const attributeName = this.getAttributeName( builder );
  22472. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  22473. let result;
  22474. if ( geometryAttribute === true ) {
  22475. result = super.generate( builder );
  22476. } else {
  22477. // Vertex color fallback should be white
  22478. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  22479. }
  22480. return result;
  22481. }
  22482. serialize( data ) {
  22483. super.serialize( data );
  22484. data.index = this.index;
  22485. }
  22486. deserialize( data ) {
  22487. super.deserialize( data );
  22488. this.index = data.index;
  22489. }
  22490. }
  22491. /**
  22492. * TSL function for creating a reference node.
  22493. *
  22494. * @tsl
  22495. * @function
  22496. * @param {number} index - The attribute index.
  22497. * @returns {VertexColorNode}
  22498. */
  22499. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  22500. /**
  22501. * A node for representing the uv coordinates of points.
  22502. *
  22503. * Can only be used with a WebGL backend. In WebGPU, point
  22504. * primitives always have the size of one pixel and can thus
  22505. * can't be used as sprite-like objects that display textures.
  22506. *
  22507. * @augments Node
  22508. */
  22509. class PointUVNode extends Node {
  22510. static get type() {
  22511. return 'PointUVNode';
  22512. }
  22513. /**
  22514. * Constructs a new point uv node.
  22515. */
  22516. constructor() {
  22517. super( 'vec2' );
  22518. /**
  22519. * This flag can be used for type testing.
  22520. *
  22521. * @type {boolean}
  22522. * @readonly
  22523. * @default true
  22524. */
  22525. this.isPointUVNode = true;
  22526. }
  22527. generate( /*builder*/ ) {
  22528. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  22529. }
  22530. }
  22531. /**
  22532. * TSL object that represents the uv coordinates of points.
  22533. *
  22534. * @tsl
  22535. * @type {PointUVNode}
  22536. */
  22537. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  22538. const _e1 = /*@__PURE__*/ new Euler();
  22539. const _m1 = /*@__PURE__*/ new Matrix4();
  22540. /**
  22541. * This module allows access to a collection of scene properties. The following predefined TSL objects
  22542. * are available for easier use:
  22543. *
  22544. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  22545. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  22546. * - `backgroundRotation`: A node that represents the scene's background rotation.
  22547. *
  22548. * @augments Node
  22549. */
  22550. class SceneNode extends Node {
  22551. static get type() {
  22552. return 'SceneNode';
  22553. }
  22554. /**
  22555. * Constructs a new scene node.
  22556. *
  22557. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  22558. * @param {?Scene} [scene=null] - A reference to the scene.
  22559. */
  22560. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  22561. super();
  22562. /**
  22563. * The scope defines the type of scene property that is accessed.
  22564. *
  22565. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  22566. */
  22567. this.scope = scope;
  22568. /**
  22569. * A reference to the scene that is going to be accessed.
  22570. *
  22571. * @type {?Scene}
  22572. * @default null
  22573. */
  22574. this.scene = scene;
  22575. }
  22576. /**
  22577. * Depending on the scope, the method returns a different type of node that represents
  22578. * the respective scene property.
  22579. *
  22580. * @param {NodeBuilder} builder - The current node builder.
  22581. * @return {Node} The output node.
  22582. */
  22583. setup( builder ) {
  22584. const scope = this.scope;
  22585. const scene = this.scene !== null ? this.scene : builder.scene;
  22586. let output;
  22587. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  22588. output = reference( 'backgroundBlurriness', 'float', scene );
  22589. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  22590. output = reference( 'backgroundIntensity', 'float', scene );
  22591. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  22592. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  22593. const background = scene.background;
  22594. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  22595. _e1.copy( scene.backgroundRotation );
  22596. // accommodate left-handed frame
  22597. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  22598. _m1.makeRotationFromEuler( _e1 );
  22599. } else {
  22600. _m1.identity();
  22601. }
  22602. return _m1;
  22603. } );
  22604. } else {
  22605. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  22606. }
  22607. return output;
  22608. }
  22609. }
  22610. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  22611. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  22612. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  22613. /**
  22614. * TSL object that represents the scene's background blurriness.
  22615. *
  22616. * @tsl
  22617. * @type {SceneNode}
  22618. */
  22619. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  22620. /**
  22621. * TSL object that represents the scene's background intensity.
  22622. *
  22623. * @tsl
  22624. * @type {SceneNode}
  22625. */
  22626. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  22627. /**
  22628. * TSL object that represents the scene's background rotation.
  22629. *
  22630. * @tsl
  22631. * @type {SceneNode}
  22632. */
  22633. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  22634. /**
  22635. * This special version of a texture node can be used to
  22636. * write data into a storage texture with a compute shader.
  22637. *
  22638. * ```js
  22639. * const storageTexture = new THREE.StorageTexture( width, height );
  22640. *
  22641. * const computeTexture = Fn( ( { storageTexture } ) => {
  22642. *
  22643. * const posX = instanceIndex.modInt( width );
  22644. * const posY = instanceIndex.div( width );
  22645. * const indexUV = uvec2( posX, posY );
  22646. *
  22647. * // generate RGB values
  22648. *
  22649. * const r = 1;
  22650. * const g = 1;
  22651. * const b = 1;
  22652. *
  22653. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  22654. *
  22655. * } );
  22656. *
  22657. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  22658. * renderer.computeAsync( computeNode );
  22659. * ```
  22660. *
  22661. * This node can only be used with a WebGPU backend.
  22662. *
  22663. * @augments TextureNode
  22664. */
  22665. class StorageTextureNode extends TextureNode {
  22666. static get type() {
  22667. return 'StorageTextureNode';
  22668. }
  22669. /**
  22670. * Constructs a new storage texture node.
  22671. *
  22672. * @param {StorageTexture} value - The storage texture.
  22673. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22674. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22675. */
  22676. constructor( value, uvNode, storeNode = null ) {
  22677. super( value, uvNode );
  22678. /**
  22679. * The value node that should be stored in the texture.
  22680. *
  22681. * @type {?Node}
  22682. * @default null
  22683. */
  22684. this.storeNode = storeNode;
  22685. /**
  22686. * This flag can be used for type testing.
  22687. *
  22688. * @type {boolean}
  22689. * @readonly
  22690. * @default true
  22691. */
  22692. this.isStorageTextureNode = true;
  22693. /**
  22694. * The access type of the texture node.
  22695. *
  22696. * @type {string}
  22697. * @default 'writeOnly'
  22698. */
  22699. this.access = NodeAccess.WRITE_ONLY;
  22700. }
  22701. /**
  22702. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  22703. *
  22704. * @param {NodeBuilder} builder - The current node builder.
  22705. * @return {string} The input type.
  22706. */
  22707. getInputType( /*builder*/ ) {
  22708. return 'storageTexture';
  22709. }
  22710. setup( builder ) {
  22711. super.setup( builder );
  22712. const properties = builder.getNodeProperties( this );
  22713. properties.storeNode = this.storeNode;
  22714. }
  22715. /**
  22716. * Defines the node access.
  22717. *
  22718. * @param {string} value - The node access.
  22719. * @return {StorageTextureNode} A reference to this node.
  22720. */
  22721. setAccess( value ) {
  22722. this.access = value;
  22723. return this;
  22724. }
  22725. /**
  22726. * Generates the code snippet of the storage node. If no `storeNode`
  22727. * is defined, the texture node is generated as normal texture.
  22728. *
  22729. * @param {NodeBuilder} builder - The current node builder.
  22730. * @param {string} output - The current output.
  22731. * @return {string} The generated code snippet.
  22732. */
  22733. generate( builder, output ) {
  22734. let snippet;
  22735. if ( this.storeNode !== null ) {
  22736. snippet = this.generateStore( builder );
  22737. } else {
  22738. snippet = super.generate( builder, output );
  22739. }
  22740. return snippet;
  22741. }
  22742. /**
  22743. * Convenience method for configuring a read/write node access.
  22744. *
  22745. * @return {StorageTextureNode} A reference to this node.
  22746. */
  22747. toReadWrite() {
  22748. return this.setAccess( NodeAccess.READ_WRITE );
  22749. }
  22750. /**
  22751. * Convenience method for configuring a read-only node access.
  22752. *
  22753. * @return {StorageTextureNode} A reference to this node.
  22754. */
  22755. toReadOnly() {
  22756. return this.setAccess( NodeAccess.READ_ONLY );
  22757. }
  22758. /**
  22759. * Convenience method for configuring a write-only node access.
  22760. *
  22761. * @return {StorageTextureNode} A reference to this node.
  22762. */
  22763. toWriteOnly() {
  22764. return this.setAccess( NodeAccess.WRITE_ONLY );
  22765. }
  22766. /**
  22767. * Generates the code snippet of the storage texture node.
  22768. *
  22769. * @param {NodeBuilder} builder - The current node builder.
  22770. */
  22771. generateStore( builder ) {
  22772. const properties = builder.getNodeProperties( this );
  22773. const { uvNode, storeNode } = properties;
  22774. const textureProperty = super.generate( builder, 'property' );
  22775. const uvSnippet = uvNode.build( builder, 'uvec2' );
  22776. const storeSnippet = storeNode.build( builder, 'vec4' );
  22777. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  22778. builder.addLineFlowCode( snippet, this );
  22779. }
  22780. }
  22781. /**
  22782. * TSL function for creating a storage texture node.
  22783. *
  22784. * @tsl
  22785. * @function
  22786. * @param {StorageTexture} value - The storage texture.
  22787. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22788. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22789. * @returns {StorageTextureNode}
  22790. */
  22791. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  22792. /**
  22793. * TODO: Explain difference to `storageTexture()`.
  22794. *
  22795. * @tsl
  22796. * @function
  22797. * @param {StorageTexture} value - The storage texture.
  22798. * @param {Node<vec2|vec3>} uvNode - The uv node.
  22799. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  22800. * @returns {StorageTextureNode}
  22801. */
  22802. const textureStore = ( value, uvNode, storeNode ) => {
  22803. const node = storageTexture( value, uvNode, storeNode );
  22804. if ( storeNode !== null ) node.append();
  22805. return node;
  22806. };
  22807. const normal = Fn( ( { texture, uv } ) => {
  22808. const epsilon = 0.0001;
  22809. const ret = vec3().toVar();
  22810. If( uv.x.lessThan( epsilon ), () => {
  22811. ret.assign( vec3( 1, 0, 0 ) );
  22812. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  22813. ret.assign( vec3( 0, 1, 0 ) );
  22814. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  22815. ret.assign( vec3( 0, 0, 1 ) );
  22816. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  22817. ret.assign( vec3( -1, 0, 0 ) );
  22818. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  22819. ret.assign( vec3( 0, -1, 0 ) );
  22820. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  22821. ret.assign( vec3( 0, 0, -1 ) );
  22822. } ).Else( () => {
  22823. const step = 0.01;
  22824. const x = texture.sample( uv.add( vec3( -0.01, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  22825. const y = texture.sample( uv.add( vec3( 0.0, -0.01, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  22826. const z = texture.sample( uv.add( vec3( 0.0, 0.0, -0.01 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  22827. ret.assign( vec3( x, y, z ) );
  22828. } );
  22829. return ret.normalize();
  22830. } );
  22831. /**
  22832. * This type of uniform node represents a 3D texture.
  22833. *
  22834. * @augments TextureNode
  22835. */
  22836. class Texture3DNode extends TextureNode {
  22837. static get type() {
  22838. return 'Texture3DNode';
  22839. }
  22840. /**
  22841. * Constructs a new 3D texture node.
  22842. *
  22843. * @param {Data3DTexture} value - The 3D texture.
  22844. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  22845. * @param {?Node<int>} [levelNode=null] - The level node.
  22846. */
  22847. constructor( value, uvNode = null, levelNode = null ) {
  22848. super( value, uvNode, levelNode );
  22849. /**
  22850. * This flag can be used for type testing.
  22851. *
  22852. * @type {boolean}
  22853. * @readonly
  22854. * @default true
  22855. */
  22856. this.isTexture3DNode = true;
  22857. }
  22858. /**
  22859. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  22860. *
  22861. * @param {NodeBuilder} builder - The current node builder.
  22862. * @return {string} The input type.
  22863. */
  22864. getInputType( /*builder*/ ) {
  22865. return 'texture3D';
  22866. }
  22867. /**
  22868. * Returns a default uv node which is in context of 3D textures a three-dimensional
  22869. * uv node.
  22870. *
  22871. * @return {Node<vec3>} The default uv node.
  22872. */
  22873. getDefaultUV() {
  22874. return vec3( 0.5, 0.5, 0.5 );
  22875. }
  22876. /**
  22877. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  22878. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  22879. *
  22880. * @param {boolean} value - The update toggle.
  22881. */
  22882. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  22883. /**
  22884. * Overwrites the default implementation to return the unmodified uv node.
  22885. *
  22886. * @param {NodeBuilder} builder - The current node builder.
  22887. * @param {Node} uvNode - The uv node to setup.
  22888. * @return {Node} The unmodified uv node.
  22889. */
  22890. setupUV( builder, uvNode ) {
  22891. const texture = this.value;
  22892. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  22893. if ( this.sampler ) {
  22894. uvNode = uvNode.flipY();
  22895. } else {
  22896. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  22897. }
  22898. }
  22899. return uvNode;
  22900. }
  22901. /**
  22902. * Generates the uv code snippet.
  22903. *
  22904. * @param {NodeBuilder} builder - The current node builder.
  22905. * @param {Node} uvNode - The uv node to generate code for.
  22906. * @return {string} The generated code snippet.
  22907. */
  22908. generateUV( builder, uvNode ) {
  22909. return uvNode.build( builder, 'vec3' );
  22910. }
  22911. /**
  22912. * TODO.
  22913. *
  22914. * @param {Node<vec3>} uvNode - The uv node .
  22915. * @return {Node<vec3>} TODO.
  22916. */
  22917. normal( uvNode ) {
  22918. return normal( { texture: this, uv: uvNode } );
  22919. }
  22920. }
  22921. /**
  22922. * TSL function for creating a 3D texture node.
  22923. *
  22924. * @tsl
  22925. * @function
  22926. * @param {Data3DTexture} value - The 3D texture.
  22927. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  22928. * @param {?Node<int>} [levelNode=null] - The level node.
  22929. * @returns {Texture3DNode}
  22930. */
  22931. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  22932. /**
  22933. * A special type of reference node that allows to link values in
  22934. * `userData` fields to node objects.
  22935. * ```js
  22936. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  22937. *
  22938. * const material = new THREE.SpriteNodeMaterial();
  22939. * material.rotationNode = userData( 'rotation', 'float' );
  22940. * ```
  22941. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  22942. * will automatically be updated when the `rotation` user data field changes.
  22943. *
  22944. * @augments ReferenceNode
  22945. */
  22946. class UserDataNode extends ReferenceNode {
  22947. static get type() {
  22948. return 'UserDataNode';
  22949. }
  22950. /**
  22951. * Constructs a new user data node.
  22952. *
  22953. * @param {string} property - The property name that should be referenced by the node.
  22954. * @param {string} inputType - The node data type of the reference.
  22955. * @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.
  22956. */
  22957. constructor( property, inputType, userData = null ) {
  22958. super( property, inputType, userData );
  22959. /**
  22960. * A reference to the `userData` object. If not provided, the `userData`
  22961. * property of the 3D object that uses the node material is evaluated.
  22962. *
  22963. * @type {?Object}
  22964. * @default null
  22965. */
  22966. this.userData = userData;
  22967. }
  22968. /**
  22969. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  22970. * `userData` field.
  22971. *
  22972. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  22973. * @return {Object} A reference to the `userData` field.
  22974. */
  22975. updateReference( state ) {
  22976. this.reference = this.userData !== null ? this.userData : state.object.userData;
  22977. return this.reference;
  22978. }
  22979. }
  22980. /**
  22981. * TSL function for creating a user data node.
  22982. *
  22983. * @tsl
  22984. * @function
  22985. * @param {string} name - The property name that should be referenced by the node.
  22986. * @param {string} inputType - The node data type of the reference.
  22987. * @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.
  22988. * @returns {UserDataNode}
  22989. */
  22990. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  22991. const _objectData = new WeakMap();
  22992. /**
  22993. * A node for representing motion or velocity vectors. Foundation
  22994. * for advanced post processing effects like motion blur or TRAA.
  22995. *
  22996. * The node keeps track of the model, view and projection matrices
  22997. * of the previous frame and uses them to compute offsets in NDC space.
  22998. * These offsets represent the final velocity.
  22999. *
  23000. * @augments TempNode
  23001. */
  23002. class VelocityNode extends TempNode {
  23003. static get type() {
  23004. return 'VelocityNode';
  23005. }
  23006. /**
  23007. * Constructs a new vertex color node.
  23008. */
  23009. constructor() {
  23010. super( 'vec2' );
  23011. /**
  23012. * The current projection matrix.
  23013. *
  23014. * @type {?Matrix4}
  23015. * @default null
  23016. */
  23017. this.projectionMatrix = null;
  23018. /**
  23019. * Overwritten since velocity nodes are updated per object.
  23020. *
  23021. * @type {string}
  23022. * @default 'object'
  23023. */
  23024. this.updateType = NodeUpdateType.OBJECT;
  23025. /**
  23026. * Overwritten since velocity nodes save data after the update.
  23027. *
  23028. * @type {string}
  23029. * @default 'object'
  23030. */
  23031. this.updateAfterType = NodeUpdateType.OBJECT;
  23032. /**
  23033. * Uniform node representing the previous model matrix in world space.
  23034. *
  23035. * @type {UniformNode<mat4>}
  23036. * @default null
  23037. */
  23038. this.previousModelWorldMatrix = uniform( new Matrix4() );
  23039. /**
  23040. * Uniform node representing the previous projection matrix.
  23041. *
  23042. * @type {UniformNode<mat4>}
  23043. * @default null
  23044. */
  23045. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  23046. /**
  23047. * Uniform node representing the previous view matrix.
  23048. *
  23049. * @type {UniformNode<mat4>}
  23050. * @default null
  23051. */
  23052. this.previousCameraViewMatrix = uniform( new Matrix4() );
  23053. }
  23054. /**
  23055. * Sets the given projection matrix.
  23056. *
  23057. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  23058. */
  23059. setProjectionMatrix( projectionMatrix ) {
  23060. this.projectionMatrix = projectionMatrix;
  23061. }
  23062. /**
  23063. * Updates velocity specific uniforms.
  23064. *
  23065. * @param {NodeFrame} frame - A reference to the current node frame.
  23066. */
  23067. update( { frameId, camera, object } ) {
  23068. const previousModelMatrix = getPreviousMatrix( object );
  23069. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  23070. //
  23071. const cameraData = getData( camera );
  23072. if ( cameraData.frameId !== frameId ) {
  23073. cameraData.frameId = frameId;
  23074. if ( cameraData.previousProjectionMatrix === undefined ) {
  23075. cameraData.previousProjectionMatrix = new Matrix4();
  23076. cameraData.previousCameraViewMatrix = new Matrix4();
  23077. cameraData.currentProjectionMatrix = new Matrix4();
  23078. cameraData.currentCameraViewMatrix = new Matrix4();
  23079. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23080. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  23081. } else {
  23082. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  23083. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  23084. }
  23085. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23086. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  23087. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  23088. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  23089. }
  23090. }
  23091. /**
  23092. * Overwritten to updated velocity specific uniforms.
  23093. *
  23094. * @param {NodeFrame} frame - A reference to the current node frame.
  23095. */
  23096. updateAfter( { object } ) {
  23097. getPreviousMatrix( object ).copy( object.matrixWorld );
  23098. }
  23099. /**
  23100. * Implements the velocity computation based on the previous and current vertex data.
  23101. *
  23102. * @param {NodeBuilder} builder - A reference to the current node builder.
  23103. * @return {Node<vec2>} The motion vector.
  23104. */
  23105. setup( /*builder*/ ) {
  23106. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  23107. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  23108. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23109. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  23110. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  23111. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  23112. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  23113. return velocity;
  23114. }
  23115. }
  23116. function getData( object ) {
  23117. let objectData = _objectData.get( object );
  23118. if ( objectData === undefined ) {
  23119. objectData = {};
  23120. _objectData.set( object, objectData );
  23121. }
  23122. return objectData;
  23123. }
  23124. function getPreviousMatrix( object, index = 0 ) {
  23125. const objectData = getData( object );
  23126. let matrix = objectData[ index ];
  23127. if ( matrix === undefined ) {
  23128. objectData[ index ] = matrix = new Matrix4();
  23129. }
  23130. return matrix;
  23131. }
  23132. /**
  23133. * TSL object that represents the velocity of a render pass.
  23134. *
  23135. * @tsl
  23136. * @type {VelocityNode}
  23137. */
  23138. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  23139. /**
  23140. * Represents a "Color Burn" blend mode.
  23141. *
  23142. * It's designed to darken the base layer's colors based on the color of the blend layer.
  23143. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  23144. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  23145. *
  23146. * @tsl
  23147. * @function
  23148. * @param {Node<vec3>} base - The base color.
  23149. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  23150. * @return {Node<vec3>} The result.
  23151. */
  23152. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23153. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  23154. } ).setLayout( {
  23155. name: 'blendBurn',
  23156. type: 'vec3',
  23157. inputs: [
  23158. { name: 'base', type: 'vec3' },
  23159. { name: 'blend', type: 'vec3' }
  23160. ]
  23161. } );
  23162. /**
  23163. * Represents a "Color Dodge" blend mode.
  23164. *
  23165. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  23166. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  23167. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  23168. *
  23169. * @tsl
  23170. * @function
  23171. * @param {Node<vec3>} base - The base color.
  23172. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23173. * @return {Node<vec3>} The result.
  23174. */
  23175. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23176. return min$1( base.div( blend.oneMinus() ), 1.0 );
  23177. } ).setLayout( {
  23178. name: 'blendDodge',
  23179. type: 'vec3',
  23180. inputs: [
  23181. { name: 'base', type: 'vec3' },
  23182. { name: 'blend', type: 'vec3' }
  23183. ]
  23184. } );
  23185. /**
  23186. * Represents a "Screen" blend mode.
  23187. *
  23188. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  23189. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  23190. * effects.
  23191. *
  23192. * @tsl
  23193. * @function
  23194. * @param {Node<vec3>} base - The base color.
  23195. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23196. * @return {Node<vec3>} The result.
  23197. */
  23198. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23199. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  23200. } ).setLayout( {
  23201. name: 'blendScreen',
  23202. type: 'vec3',
  23203. inputs: [
  23204. { name: 'base', type: 'vec3' },
  23205. { name: 'blend', type: 'vec3' }
  23206. ]
  23207. } );
  23208. /**
  23209. * Represents a "Overlay" blend mode.
  23210. *
  23211. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  23212. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  23213. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  23214. *
  23215. * @tsl
  23216. * @function
  23217. * @param {Node<vec3>} base - The base color.
  23218. * @param {Node<vec3>} blend - The blend color
  23219. * @return {Node<vec3>} The result.
  23220. */
  23221. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23222. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  23223. } ).setLayout( {
  23224. name: 'blendOverlay',
  23225. type: 'vec3',
  23226. inputs: [
  23227. { name: 'base', type: 'vec3' },
  23228. { name: 'blend', type: 'vec3' }
  23229. ]
  23230. } );
  23231. /**
  23232. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  23233. * It assumes both input colors have non-premultiplied alpha.
  23234. *
  23235. * @tsl
  23236. * @function
  23237. * @param {Node<vec4>} base - The base color.
  23238. * @param {Node<vec4>} blend - The blend color
  23239. * @return {Node<vec4>} The result.
  23240. */
  23241. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23242. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  23243. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  23244. } ).setLayout( {
  23245. name: 'blendColor',
  23246. type: 'vec4',
  23247. inputs: [
  23248. { name: 'base', type: 'vec4' },
  23249. { name: 'blend', type: 'vec4' }
  23250. ]
  23251. } );
  23252. // Deprecated
  23253. /**
  23254. * @tsl
  23255. * @function
  23256. * @deprecated since r171. Use {@link blendBurn} instead.
  23257. *
  23258. * @param {...any} params
  23259. * @returns {Function}
  23260. */
  23261. const burn = ( ...params ) => { // @deprecated, r171
  23262. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  23263. return blendBurn( params );
  23264. };
  23265. /**
  23266. * @tsl
  23267. * @function
  23268. * @deprecated since r171. Use {@link blendDodge} instead.
  23269. *
  23270. * @param {...any} params
  23271. * @returns {Function}
  23272. */
  23273. const dodge = ( ...params ) => { // @deprecated, r171
  23274. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  23275. return blendDodge( params );
  23276. };
  23277. /**
  23278. * @tsl
  23279. * @function
  23280. * @deprecated since r171. Use {@link blendScreen} instead.
  23281. *
  23282. * @param {...any} params
  23283. * @returns {Function}
  23284. */
  23285. const screen = ( ...params ) => { // @deprecated, r171
  23286. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  23287. return blendScreen( params );
  23288. };
  23289. /**
  23290. * @tsl
  23291. * @function
  23292. * @deprecated since r171. Use {@link blendOverlay} instead.
  23293. *
  23294. * @param {...any} params
  23295. * @returns {Function}
  23296. */
  23297. const overlay = ( ...params ) => { // @deprecated, r171
  23298. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  23299. return blendOverlay( params );
  23300. };
  23301. /**
  23302. * Computes a grayscale value for the given RGB color value.
  23303. *
  23304. * @tsl
  23305. * @function
  23306. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  23307. * @return {Node<vec3>} The grayscale color.
  23308. */
  23309. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23310. return luminance( color.rgb );
  23311. } );
  23312. /**
  23313. * Super-saturates or desaturates the given RGB color.
  23314. *
  23315. * @tsl
  23316. * @function
  23317. * @param {Node<vec3>} color - The input color.
  23318. * @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.
  23319. * @return {Node<vec3>} The saturated color.
  23320. */
  23321. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23322. return adjustment.mix( luminance( color.rgb ), color.rgb );
  23323. } );
  23324. /**
  23325. * Selectively enhance the intensity of less saturated RGB colors. Can result
  23326. * in a more natural and visually appealing image with enhanced color depth
  23327. * compared to {@link ColorAdjustment#saturation}.
  23328. *
  23329. * @tsl
  23330. * @function
  23331. * @param {Node<vec3>} color - The input color.
  23332. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  23333. * @return {Node<vec3>} The updated color.
  23334. */
  23335. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23336. const average = add( color.r, color.g, color.b ).div( 3.0 );
  23337. const mx = color.r.max( color.g.max( color.b ) );
  23338. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  23339. return mix( color.rgb, mx, amt );
  23340. } );
  23341. /**
  23342. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  23343. *
  23344. * @tsl
  23345. * @function
  23346. * @param {Node<vec3>} color - The input color.
  23347. * @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.
  23348. * @return {Node<vec3>} The updated color.
  23349. */
  23350. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23351. const k = vec3( 0.57735, 0.57735, 0.57735 );
  23352. const cosAngle = adjustment.cos();
  23353. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  23354. } );
  23355. /**
  23356. * Computes the luminance for the given RGB color value.
  23357. *
  23358. * @tsl
  23359. * @function
  23360. * @param {Node<vec3>} color - The color value to compute the luminance for.
  23361. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  23362. * @return {Node<vec3>} The luminance.
  23363. */
  23364. const luminance = (
  23365. color,
  23366. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  23367. ) => dot( color, luminanceCoefficients );
  23368. /**
  23369. * Color Decision List (CDL) v1.2
  23370. *
  23371. * Compact representation of color grading information, defined by slope, offset, power, and
  23372. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  23373. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  23374. *
  23375. * @tsl
  23376. * @function
  23377. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  23378. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  23379. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  23380. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  23381. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  23382. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  23383. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  23384. *
  23385. * References:
  23386. * - ASC CDL v1.2
  23387. * - {@link https://blender.stackexchange.com/a/55239/43930}
  23388. * - {@link https://docs.acescentral.com/specifications/acescc/}
  23389. */
  23390. const cdl = /*@__PURE__*/ Fn( ( [
  23391. color,
  23392. slope = vec3( 1 ),
  23393. offset = vec3( 0 ),
  23394. power = vec3( 1 ),
  23395. saturation = float( 1 ),
  23396. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  23397. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  23398. ] ) => {
  23399. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  23400. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  23401. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  23402. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  23403. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  23404. const pv = v.pow( power ).toVar();
  23405. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  23406. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  23407. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  23408. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  23409. return vec4( v.rgb, color.a );
  23410. } );
  23411. /**
  23412. * Represents a posterize effect which reduces the number of colors
  23413. * in an image, resulting in a more blocky and stylized appearance.
  23414. *
  23415. * @augments TempNode
  23416. */
  23417. class PosterizeNode extends TempNode {
  23418. static get type() {
  23419. return 'PosterizeNode';
  23420. }
  23421. /**
  23422. * Constructs a new posterize node.
  23423. *
  23424. * @param {Node} sourceNode - The input color.
  23425. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  23426. */
  23427. constructor( sourceNode, stepsNode ) {
  23428. super();
  23429. /**
  23430. * The input color.
  23431. *
  23432. * @type {Node}
  23433. */
  23434. this.sourceNode = sourceNode;
  23435. /**
  23436. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  23437. *
  23438. * @type {Node}
  23439. */
  23440. this.stepsNode = stepsNode;
  23441. }
  23442. setup() {
  23443. const { sourceNode, stepsNode } = this;
  23444. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  23445. }
  23446. }
  23447. /**
  23448. * TSL function for creating a posterize node.
  23449. *
  23450. * @tsl
  23451. * @function
  23452. * @param {Node} sourceNode - The input color.
  23453. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  23454. * @returns {PosterizeNode}
  23455. */
  23456. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  23457. const _size = /*@__PURE__*/ new Vector2();
  23458. /**
  23459. * Represents the texture of a pass node.
  23460. *
  23461. * @augments TextureNode
  23462. */
  23463. class PassTextureNode extends TextureNode {
  23464. static get type() {
  23465. return 'PassTextureNode';
  23466. }
  23467. /**
  23468. * Constructs a new pass texture node.
  23469. *
  23470. * @param {PassNode} passNode - The pass node.
  23471. * @param {Texture} texture - The output texture.
  23472. */
  23473. constructor( passNode, texture ) {
  23474. super( texture );
  23475. /**
  23476. * A reference to the pass node.
  23477. *
  23478. * @type {PassNode}
  23479. */
  23480. this.passNode = passNode;
  23481. this.setUpdateMatrix( false );
  23482. }
  23483. setup( builder ) {
  23484. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  23485. return super.setup( builder );
  23486. }
  23487. clone() {
  23488. return new this.constructor( this.passNode, this.value );
  23489. }
  23490. }
  23491. /**
  23492. * An extension of `PassTextureNode` which allows to manage more than one
  23493. * internal texture. Relevant for the `getPreviousTexture()` related API.
  23494. *
  23495. * @augments PassTextureNode
  23496. */
  23497. class PassMultipleTextureNode extends PassTextureNode {
  23498. static get type() {
  23499. return 'PassMultipleTextureNode';
  23500. }
  23501. /**
  23502. * Constructs a new pass texture node.
  23503. *
  23504. * @param {PassNode} passNode - The pass node.
  23505. * @param {string} textureName - The output texture name.
  23506. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  23507. */
  23508. constructor( passNode, textureName, previousTexture = false ) {
  23509. // null is passed to the super call since this class does not
  23510. // use an external texture for rendering pass data into. Instead
  23511. // the texture is managed by the pass node itself
  23512. super( passNode, null );
  23513. /**
  23514. * The output texture name.
  23515. *
  23516. * @type {string}
  23517. */
  23518. this.textureName = textureName;
  23519. /**
  23520. * Whether previous frame data should be used or not.
  23521. *
  23522. * @type {boolean}
  23523. */
  23524. this.previousTexture = previousTexture;
  23525. }
  23526. /**
  23527. * Updates the texture reference of this node.
  23528. */
  23529. updateTexture() {
  23530. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  23531. }
  23532. setup( builder ) {
  23533. this.updateTexture();
  23534. return super.setup( builder );
  23535. }
  23536. clone() {
  23537. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  23538. }
  23539. }
  23540. /**
  23541. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  23542. * This pass produces a render for the given scene and camera and can provide multiple outputs
  23543. * via MRT for further processing.
  23544. *
  23545. * ```js
  23546. * const postProcessing = new PostProcessing( renderer );
  23547. *
  23548. * const scenePass = pass( scene, camera );
  23549. *
  23550. * postProcessing.outputNode = scenePass;
  23551. * ```
  23552. *
  23553. * @augments TempNode
  23554. */
  23555. class PassNode extends TempNode {
  23556. static get type() {
  23557. return 'PassNode';
  23558. }
  23559. /**
  23560. * Constructs a new pass node.
  23561. *
  23562. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  23563. * @param {Scene} scene - A reference to the scene.
  23564. * @param {Camera} camera - A reference to the camera.
  23565. * @param {Object} options - Options for the internal render target.
  23566. */
  23567. constructor( scope, scene, camera, options = {} ) {
  23568. super( 'vec4' );
  23569. /**
  23570. * The scope of the pass. The scope determines whether the node outputs color or depth.
  23571. *
  23572. * @type {('color'|'depth')}
  23573. */
  23574. this.scope = scope;
  23575. /**
  23576. * A reference to the scene.
  23577. *
  23578. * @type {Scene}
  23579. */
  23580. this.scene = scene;
  23581. /**
  23582. * A reference to the camera.
  23583. *
  23584. * @type {Camera}
  23585. */
  23586. this.camera = camera;
  23587. /**
  23588. * Options for the internal render target.
  23589. *
  23590. * @type {Object}
  23591. */
  23592. this.options = options;
  23593. /**
  23594. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  23595. *
  23596. * @private
  23597. * @type {number}
  23598. * @default 1
  23599. */
  23600. this._pixelRatio = 1;
  23601. /**
  23602. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  23603. * @private
  23604. * @type {number}
  23605. * @default 1
  23606. */
  23607. this._width = 1;
  23608. /**
  23609. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  23610. * @private
  23611. * @type {number}
  23612. * @default 1
  23613. */
  23614. this._height = 1;
  23615. const depthTexture = new DepthTexture();
  23616. depthTexture.isRenderTargetTexture = true;
  23617. //depthTexture.type = FloatType;
  23618. depthTexture.name = 'depth';
  23619. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  23620. renderTarget.texture.name = 'output';
  23621. renderTarget.depthTexture = depthTexture;
  23622. /**
  23623. * The pass's render target.
  23624. *
  23625. * @type {RenderTarget}
  23626. */
  23627. this.renderTarget = renderTarget;
  23628. /**
  23629. * A dictionary holding the internal result textures.
  23630. *
  23631. * @private
  23632. * @type {Object<string, Texture>}
  23633. */
  23634. this._textures = {
  23635. output: renderTarget.texture,
  23636. depth: depthTexture
  23637. };
  23638. /**
  23639. * A dictionary holding the internal texture nodes.
  23640. *
  23641. * @private
  23642. * @type {Object<string, TextureNode>}
  23643. */
  23644. this._textureNodes = {};
  23645. /**
  23646. * A dictionary holding the internal depth nodes.
  23647. *
  23648. * @private
  23649. * @type {Object}
  23650. */
  23651. this._linearDepthNodes = {};
  23652. /**
  23653. * A dictionary holding the internal viewZ nodes.
  23654. *
  23655. * @private
  23656. * @type {Object}
  23657. */
  23658. this._viewZNodes = {};
  23659. /**
  23660. * A dictionary holding the texture data of the previous frame.
  23661. * Used for computing velocity/motion vectors.
  23662. *
  23663. * @private
  23664. * @type {Object<string, Texture>}
  23665. */
  23666. this._previousTextures = {};
  23667. /**
  23668. * A dictionary holding the texture nodes of the previous frame.
  23669. * Used for computing velocity/motion vectors.
  23670. *
  23671. * @private
  23672. * @type {Object<string, TextureNode>}
  23673. */
  23674. this._previousTextureNodes = {};
  23675. /**
  23676. * The `near` property of the camera as a uniform.
  23677. *
  23678. * @private
  23679. * @type {UniformNode}
  23680. */
  23681. this._cameraNear = uniform( 0 );
  23682. /**
  23683. * The `far` property of the camera as a uniform.
  23684. *
  23685. * @private
  23686. * @type {UniformNode}
  23687. */
  23688. this._cameraFar = uniform( 0 );
  23689. /**
  23690. * A MRT node configuring the MRT settings.
  23691. *
  23692. * @private
  23693. * @type {?MRTNode}
  23694. * @default null
  23695. */
  23696. this._mrt = null;
  23697. this._layers = null;
  23698. this._resolution = 1;
  23699. /**
  23700. * This flag can be used for type testing.
  23701. *
  23702. * @type {boolean}
  23703. * @readonly
  23704. * @default true
  23705. */
  23706. this.isPassNode = true;
  23707. /**
  23708. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  23709. * scene once per frame in its {@link PassNode#updateBefore} method.
  23710. *
  23711. * @type {string}
  23712. * @default 'frame'
  23713. */
  23714. this.updateBeforeType = NodeUpdateType.FRAME;
  23715. }
  23716. /**
  23717. * Sets the resolution for the pass.
  23718. * The resolution is a factor that is multiplied with the renderer's width and height.
  23719. *
  23720. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  23721. * @return {PassNode} A reference to this pass.
  23722. */
  23723. setResolution( resolution ) {
  23724. this._resolution = resolution;
  23725. return this;
  23726. }
  23727. /**
  23728. * Gets the current resolution of the pass.
  23729. *
  23730. * @return {number} The current resolution. A value of `1` means full resolution.
  23731. * @default 1
  23732. */
  23733. getResolution() {
  23734. return this._resolution;
  23735. }
  23736. setLayers( layers ) {
  23737. this._layers = layers;
  23738. return this;
  23739. }
  23740. getLayers() {
  23741. return this._layers;
  23742. }
  23743. /**
  23744. * Sets the given MRT node to setup MRT for this pass.
  23745. *
  23746. * @param {MRTNode} mrt - The MRT object.
  23747. * @return {PassNode} A reference to this pass.
  23748. */
  23749. setMRT( mrt ) {
  23750. this._mrt = mrt;
  23751. return this;
  23752. }
  23753. /**
  23754. * Returns the current MRT node.
  23755. *
  23756. * @return {MRTNode} The current MRT node.
  23757. */
  23758. getMRT() {
  23759. return this._mrt;
  23760. }
  23761. /**
  23762. * The method is overwritten so it always returns `true`.
  23763. *
  23764. * @return {boolean} Whether this node is global or not.
  23765. */
  23766. isGlobal() {
  23767. return true;
  23768. }
  23769. /**
  23770. * Returns the texture for the given output name.
  23771. *
  23772. * @param {string} name - The output name to get the texture for.
  23773. * @return {Texture} The texture.
  23774. */
  23775. getTexture( name ) {
  23776. let texture = this._textures[ name ];
  23777. if ( texture === undefined ) {
  23778. const refTexture = this.renderTarget.texture;
  23779. texture = refTexture.clone();
  23780. texture.name = name;
  23781. this._textures[ name ] = texture;
  23782. this.renderTarget.textures.push( texture );
  23783. }
  23784. return texture;
  23785. }
  23786. /**
  23787. * Returns the texture holding the data of the previous frame for the given output name.
  23788. *
  23789. * @param {string} name - The output name to get the texture for.
  23790. * @return {Texture} The texture holding the data of the previous frame.
  23791. */
  23792. getPreviousTexture( name ) {
  23793. let texture = this._previousTextures[ name ];
  23794. if ( texture === undefined ) {
  23795. texture = this.getTexture( name ).clone();
  23796. this._previousTextures[ name ] = texture;
  23797. }
  23798. return texture;
  23799. }
  23800. /**
  23801. * Switches current and previous textures for the given output name.
  23802. *
  23803. * @param {string} name - The output name.
  23804. */
  23805. toggleTexture( name ) {
  23806. const prevTexture = this._previousTextures[ name ];
  23807. if ( prevTexture !== undefined ) {
  23808. const texture = this._textures[ name ];
  23809. const index = this.renderTarget.textures.indexOf( texture );
  23810. this.renderTarget.textures[ index ] = prevTexture;
  23811. this._textures[ name ] = prevTexture;
  23812. this._previousTextures[ name ] = texture;
  23813. this._textureNodes[ name ].updateTexture();
  23814. this._previousTextureNodes[ name ].updateTexture();
  23815. }
  23816. }
  23817. /**
  23818. * Returns the texture node for the given output name.
  23819. *
  23820. * @param {string} [name='output'] - The output name to get the texture node for.
  23821. * @return {TextureNode} The texture node.
  23822. */
  23823. getTextureNode( name = 'output' ) {
  23824. let textureNode = this._textureNodes[ name ];
  23825. if ( textureNode === undefined ) {
  23826. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  23827. textureNode.updateTexture();
  23828. this._textureNodes[ name ] = textureNode;
  23829. }
  23830. return textureNode;
  23831. }
  23832. /**
  23833. * Returns the previous texture node for the given output name.
  23834. *
  23835. * @param {string} [name='output'] - The output name to get the previous texture node for.
  23836. * @return {TextureNode} The previous texture node.
  23837. */
  23838. getPreviousTextureNode( name = 'output' ) {
  23839. let textureNode = this._previousTextureNodes[ name ];
  23840. if ( textureNode === undefined ) {
  23841. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  23842. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  23843. textureNode.updateTexture();
  23844. this._previousTextureNodes[ name ] = textureNode;
  23845. }
  23846. return textureNode;
  23847. }
  23848. /**
  23849. * Returns a viewZ node of this pass.
  23850. *
  23851. * @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.
  23852. * @return {Node} The viewZ node.
  23853. */
  23854. getViewZNode( name = 'depth' ) {
  23855. let viewZNode = this._viewZNodes[ name ];
  23856. if ( viewZNode === undefined ) {
  23857. const cameraNear = this._cameraNear;
  23858. const cameraFar = this._cameraFar;
  23859. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  23860. }
  23861. return viewZNode;
  23862. }
  23863. /**
  23864. * Returns a linear depth node of this pass.
  23865. *
  23866. * @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.
  23867. * @return {Node} The linear depth node.
  23868. */
  23869. getLinearDepthNode( name = 'depth' ) {
  23870. let linearDepthNode = this._linearDepthNodes[ name ];
  23871. if ( linearDepthNode === undefined ) {
  23872. const cameraNear = this._cameraNear;
  23873. const cameraFar = this._cameraFar;
  23874. const viewZNode = this.getViewZNode( name );
  23875. // TODO: just if ( builder.camera.isPerspectiveCamera )
  23876. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  23877. }
  23878. return linearDepthNode;
  23879. }
  23880. setup( { renderer } ) {
  23881. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  23882. // TODO: Disable MSAA for WebGL backend for now
  23883. if ( renderer.backend.isWebGLBackend === true ) {
  23884. this.renderTarget.samples = 0;
  23885. }
  23886. this.renderTarget.texture.type = renderer.getColorBufferType();
  23887. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  23888. }
  23889. updateBefore( frame ) {
  23890. const { renderer } = frame;
  23891. const { scene } = this;
  23892. let camera;
  23893. let pixelRatio;
  23894. const outputRenderTarget = renderer.getOutputRenderTarget();
  23895. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  23896. pixelRatio = 1;
  23897. camera = renderer.xr.getCamera();
  23898. renderer.xr.updateCamera( camera );
  23899. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  23900. } else {
  23901. camera = this.camera;
  23902. pixelRatio = renderer.getPixelRatio();
  23903. renderer.getSize( _size );
  23904. }
  23905. this._pixelRatio = pixelRatio;
  23906. this.setSize( _size.width, _size.height );
  23907. const currentRenderTarget = renderer.getRenderTarget();
  23908. const currentMRT = renderer.getMRT();
  23909. const currentMask = camera.layers.mask;
  23910. this._cameraNear.value = camera.near;
  23911. this._cameraFar.value = camera.far;
  23912. if ( this._layers !== null ) {
  23913. camera.layers.mask = this._layers.mask;
  23914. }
  23915. for ( const name in this._previousTextures ) {
  23916. this.toggleTexture( name );
  23917. }
  23918. renderer.setRenderTarget( this.renderTarget );
  23919. renderer.setMRT( this._mrt );
  23920. renderer.render( scene, camera );
  23921. renderer.setRenderTarget( currentRenderTarget );
  23922. renderer.setMRT( currentMRT );
  23923. camera.layers.mask = currentMask;
  23924. }
  23925. /**
  23926. * Sets the size of the pass's render target. Honors the pixel ratio.
  23927. *
  23928. * @param {number} width - The width to set.
  23929. * @param {number} height - The height to set.
  23930. */
  23931. setSize( width, height ) {
  23932. this._width = width;
  23933. this._height = height;
  23934. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  23935. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  23936. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23937. }
  23938. /**
  23939. * Sets the pixel ratio the pass's render target and updates the size.
  23940. *
  23941. * @param {number} pixelRatio - The pixel ratio to set.
  23942. */
  23943. setPixelRatio( pixelRatio ) {
  23944. this._pixelRatio = pixelRatio;
  23945. this.setSize( this._width, this._height );
  23946. }
  23947. /**
  23948. * Frees internal resources. Should be called when the node is no longer in use.
  23949. */
  23950. dispose() {
  23951. this.renderTarget.dispose();
  23952. }
  23953. }
  23954. /**
  23955. * @static
  23956. * @type {'color'}
  23957. * @default 'color'
  23958. */
  23959. PassNode.COLOR = 'color';
  23960. /**
  23961. * @static
  23962. * @type {'depth'}
  23963. * @default 'depth'
  23964. */
  23965. PassNode.DEPTH = 'depth';
  23966. /**
  23967. * TSL function for creating a pass node.
  23968. *
  23969. * @tsl
  23970. * @function
  23971. * @param {Scene} scene - A reference to the scene.
  23972. * @param {Camera} camera - A reference to the camera.
  23973. * @param {Object} options - Options for the internal render target.
  23974. * @returns {PassNode}
  23975. */
  23976. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  23977. /**
  23978. * TSL function for creating a pass texture node.
  23979. *
  23980. * @tsl
  23981. * @function
  23982. * @param {PassNode} pass - The pass node.
  23983. * @param {Texture} texture - The output texture.
  23984. * @returns {PassTextureNode}
  23985. */
  23986. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  23987. /**
  23988. * TSL function for creating a depth pass node.
  23989. *
  23990. * @tsl
  23991. * @function
  23992. * @param {Scene} scene - A reference to the scene.
  23993. * @param {Camera} camera - A reference to the camera.
  23994. * @param {Object} options - Options for the internal render target.
  23995. * @returns {PassNode}
  23996. */
  23997. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  23998. /**
  23999. * Represents a render pass for producing a toon outline effect on compatible objects.
  24000. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  24001. * will receive the outline.
  24002. *
  24003. * ```js
  24004. * const postProcessing = new PostProcessing( renderer );
  24005. *
  24006. * const scenePass = toonOutlinePass( scene, camera );
  24007. *
  24008. * postProcessing.outputNode = scenePass;
  24009. * ```
  24010. * @augments PassNode
  24011. */
  24012. class ToonOutlinePassNode extends PassNode {
  24013. static get type() {
  24014. return 'ToonOutlinePassNode';
  24015. }
  24016. /**
  24017. * Constructs a new outline pass node.
  24018. *
  24019. * @param {Scene} scene - A reference to the scene.
  24020. * @param {Camera} camera - A reference to the camera.
  24021. * @param {Node} colorNode - Defines the outline's color.
  24022. * @param {Node} thicknessNode - Defines the outline's thickness.
  24023. * @param {Node} alphaNode - Defines the outline's alpha.
  24024. */
  24025. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  24026. super( PassNode.COLOR, scene, camera );
  24027. /**
  24028. * Defines the outline's color.
  24029. *
  24030. * @type {Node}
  24031. */
  24032. this.colorNode = colorNode;
  24033. /**
  24034. * Defines the outline's thickness.
  24035. *
  24036. * @type {Node}
  24037. */
  24038. this.thicknessNode = thicknessNode;
  24039. /**
  24040. * Defines the outline's alpha.
  24041. *
  24042. * @type {Node}
  24043. */
  24044. this.alphaNode = alphaNode;
  24045. /**
  24046. * An internal material cache.
  24047. *
  24048. * @private
  24049. * @type {WeakMap<Material, NodeMaterial>}
  24050. */
  24051. this._materialCache = new WeakMap();
  24052. }
  24053. updateBefore( frame ) {
  24054. const { renderer } = frame;
  24055. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  24056. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  24057. // only render outline for supported materials
  24058. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  24059. if ( material.wireframe === false ) {
  24060. const outlineMaterial = this._getOutlineMaterial( material );
  24061. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  24062. }
  24063. }
  24064. // default
  24065. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  24066. } );
  24067. super.updateBefore( frame );
  24068. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  24069. }
  24070. /**
  24071. * Creates the material used for outline rendering.
  24072. *
  24073. * @private
  24074. * @return {NodeMaterial} The outline material.
  24075. */
  24076. _createMaterial() {
  24077. const material = new NodeMaterial();
  24078. material.isMeshToonOutlineMaterial = true;
  24079. material.name = 'Toon_Outline';
  24080. material.side = BackSide;
  24081. // vertex node
  24082. const outlineNormal = normalLocal.negate();
  24083. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  24084. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  24085. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  24086. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  24087. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  24088. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  24089. // color node
  24090. material.colorNode = vec4( this.colorNode, this.alphaNode );
  24091. return material;
  24092. }
  24093. /**
  24094. * For the given toon material, this method returns a corresponding
  24095. * outline material.
  24096. *
  24097. * @private
  24098. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  24099. * @return {NodeMaterial} The outline material.
  24100. */
  24101. _getOutlineMaterial( originalMaterial ) {
  24102. let outlineMaterial = this._materialCache.get( originalMaterial );
  24103. if ( outlineMaterial === undefined ) {
  24104. outlineMaterial = this._createMaterial();
  24105. this._materialCache.set( originalMaterial, outlineMaterial );
  24106. }
  24107. return outlineMaterial;
  24108. }
  24109. }
  24110. /**
  24111. * TSL function for creating a toon outline pass node.
  24112. *
  24113. * @tsl
  24114. * @function
  24115. * @param {Scene} scene - A reference to the scene.
  24116. * @param {Camera} camera - A reference to the camera.
  24117. * @param {Color} color - Defines the outline's color.
  24118. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  24119. * @param {number} [alpha=1] - Defines the outline's alpha.
  24120. * @returns {ToonOutlinePassNode}
  24121. */
  24122. 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 ) ) );
  24123. /**
  24124. * Linear tone mapping, exposure only.
  24125. *
  24126. * @tsl
  24127. * @function
  24128. * @param {Node<vec3>} color - The color that should be tone mapped.
  24129. * @param {Node<float>} exposure - The exposure.
  24130. * @return {Node<vec3>} The tone mapped color.
  24131. */
  24132. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24133. return color.mul( exposure ).clamp();
  24134. } ).setLayout( {
  24135. name: 'linearToneMapping',
  24136. type: 'vec3',
  24137. inputs: [
  24138. { name: 'color', type: 'vec3' },
  24139. { name: 'exposure', type: 'float' }
  24140. ]
  24141. } );
  24142. /**
  24143. * Reinhard tone mapping.
  24144. *
  24145. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  24146. *
  24147. * @tsl
  24148. * @function
  24149. * @param {Node<vec3>} color - The color that should be tone mapped.
  24150. * @param {Node<float>} exposure - The exposure.
  24151. * @return {Node<vec3>} The tone mapped color.
  24152. */
  24153. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24154. color = color.mul( exposure );
  24155. return color.div( color.add( 1.0 ) ).clamp();
  24156. } ).setLayout( {
  24157. name: 'reinhardToneMapping',
  24158. type: 'vec3',
  24159. inputs: [
  24160. { name: 'color', type: 'vec3' },
  24161. { name: 'exposure', type: 'float' }
  24162. ]
  24163. } );
  24164. /**
  24165. * Cineon tone mapping.
  24166. *
  24167. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  24168. *
  24169. * @tsl
  24170. * @function
  24171. * @param {Node<vec3>} color - The color that should be tone mapped.
  24172. * @param {Node<float>} exposure - The exposure.
  24173. * @return {Node<vec3>} The tone mapped color.
  24174. */
  24175. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24176. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  24177. color = color.mul( exposure );
  24178. color = color.sub( 0.004 ).max( 0.0 );
  24179. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  24180. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  24181. return a.div( b ).pow( 2.2 );
  24182. } ).setLayout( {
  24183. name: 'cineonToneMapping',
  24184. type: 'vec3',
  24185. inputs: [
  24186. { name: 'color', type: 'vec3' },
  24187. { name: 'exposure', type: 'float' }
  24188. ]
  24189. } );
  24190. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  24191. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24192. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  24193. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  24194. return a.div( b );
  24195. } );
  24196. /**
  24197. * ACESFilmic tone mapping.
  24198. *
  24199. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  24200. *
  24201. * @tsl
  24202. * @function
  24203. * @param {Node<vec3>} color - The color that should be tone mapped.
  24204. * @param {Node<float>} exposure - The exposure.
  24205. * @return {Node<vec3>} The tone mapped color.
  24206. */
  24207. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24208. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  24209. const ACESInputMat = mat3(
  24210. 0.59719, 0.35458, 0.04823,
  24211. 0.07600, 0.90834, 0.01566,
  24212. 0.02840, 0.13383, 0.83777
  24213. );
  24214. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  24215. const ACESOutputMat = mat3(
  24216. 1.60475, -0.53108, -0.07367,
  24217. -0.10208, 1.10813, -605e-5,
  24218. -327e-5, -0.07276, 1.07602
  24219. );
  24220. color = color.mul( exposure ).div( 0.6 );
  24221. color = ACESInputMat.mul( color );
  24222. // Apply RRT and ODT
  24223. color = RRTAndODTFit( color );
  24224. color = ACESOutputMat.mul( color );
  24225. // Clamp to [0, 1]
  24226. return color.clamp();
  24227. } ).setLayout( {
  24228. name: 'acesFilmicToneMapping',
  24229. type: 'vec3',
  24230. inputs: [
  24231. { name: 'color', type: 'vec3' },
  24232. { name: 'exposure', type: 'float' }
  24233. ]
  24234. } );
  24235. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, -0.1246, -0.0182 ), vec3( -0.5876, 1.1329, -0.1006 ), vec3( -0.0728, -83e-4, 1.1187 ) );
  24236. 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 ) );
  24237. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  24238. const x = vec3( x_immutable ).toVar();
  24239. const x2 = vec3( x.mul( x ) ).toVar();
  24240. const x4 = vec3( x2.mul( x2 ) ).toVar();
  24241. 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 ) ) ) );
  24242. } );
  24243. /**
  24244. * AgX tone mapping.
  24245. *
  24246. * @tsl
  24247. * @function
  24248. * @param {Node<vec3>} color - The color that should be tone mapped.
  24249. * @param {Node<float>} exposure - The exposure.
  24250. * @return {Node<vec3>} The tone mapped color.
  24251. */
  24252. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24253. const colortone = vec3( color ).toVar();
  24254. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  24255. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  24256. const AgxMinEv = float( -12.47393 );
  24257. const AgxMaxEv = float( 4.026069 );
  24258. colortone.mulAssign( exposure );
  24259. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  24260. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  24261. colortone.assign( max$1( colortone, 1e-10 ) );
  24262. colortone.assign( log2( colortone ) );
  24263. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  24264. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  24265. colortone.assign( agxDefaultContrastApprox( colortone ) );
  24266. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  24267. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  24268. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  24269. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  24270. return colortone;
  24271. } ).setLayout( {
  24272. name: 'agxToneMapping',
  24273. type: 'vec3',
  24274. inputs: [
  24275. { name: 'color', type: 'vec3' },
  24276. { name: 'exposure', type: 'float' }
  24277. ]
  24278. } );
  24279. /**
  24280. * Neutral tone mapping.
  24281. *
  24282. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  24283. *
  24284. * @tsl
  24285. * @function
  24286. * @param {Node<vec3>} color - The color that should be tone mapped.
  24287. * @param {Node<float>} exposure - The exposure.
  24288. * @return {Node<vec3>} The tone mapped color.
  24289. */
  24290. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24291. const StartCompression = float( 0.8 - 0.04 );
  24292. const Desaturation = float( 0.15 );
  24293. color = color.mul( exposure );
  24294. const x = min$1( color.r, min$1( color.g, color.b ) );
  24295. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  24296. color.subAssign( offset );
  24297. const peak = max$1( color.r, max$1( color.g, color.b ) );
  24298. If( peak.lessThan( StartCompression ), () => {
  24299. return color;
  24300. } );
  24301. const d = sub( 1, StartCompression );
  24302. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  24303. color.mulAssign( newPeak.div( peak ) );
  24304. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  24305. return mix( color, vec3( newPeak ), g );
  24306. } ).setLayout( {
  24307. name: 'neutralToneMapping',
  24308. type: 'vec3',
  24309. inputs: [
  24310. { name: 'color', type: 'vec3' },
  24311. { name: 'exposure', type: 'float' }
  24312. ]
  24313. } );
  24314. /**
  24315. * This class represents native code sections. It is the base
  24316. * class for modules like {@link FunctionNode} which allows to implement
  24317. * functions with native shader languages.
  24318. *
  24319. * @augments Node
  24320. */
  24321. class CodeNode extends Node {
  24322. static get type() {
  24323. return 'CodeNode';
  24324. }
  24325. /**
  24326. * Constructs a new code node.
  24327. *
  24328. * @param {string} [code=''] - The native code.
  24329. * @param {Array<Node>} [includes=[]] - An array of includes.
  24330. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24331. */
  24332. constructor( code = '', includes = [], language = '' ) {
  24333. super( 'code' );
  24334. /**
  24335. * This flag can be used for type testing.
  24336. *
  24337. * @type {boolean}
  24338. * @readonly
  24339. * @default true
  24340. */
  24341. this.isCodeNode = true;
  24342. /**
  24343. * The native code.
  24344. *
  24345. * @type {string}
  24346. * @default ''
  24347. */
  24348. this.code = code;
  24349. /**
  24350. * An array of includes
  24351. *
  24352. * @type {Array<Node>}
  24353. * @default []
  24354. */
  24355. this.includes = includes;
  24356. /**
  24357. * The used language.
  24358. *
  24359. * @type {('js'|'wgsl'|'glsl')}
  24360. * @default ''
  24361. */
  24362. this.language = language;
  24363. }
  24364. /**
  24365. * The method is overwritten so it always returns `true`.
  24366. *
  24367. * @return {boolean} Whether this node is global or not.
  24368. */
  24369. isGlobal() {
  24370. return true;
  24371. }
  24372. /**
  24373. * Sets the includes of this code node.
  24374. *
  24375. * @param {Array<Node>} includes - The includes to set.
  24376. * @return {CodeNode} A reference to this node.
  24377. */
  24378. setIncludes( includes ) {
  24379. this.includes = includes;
  24380. return this;
  24381. }
  24382. /**
  24383. * Returns the includes of this code node.
  24384. *
  24385. * @param {NodeBuilder} builder - The current node builder.
  24386. * @return {Array<Node>} The includes.
  24387. */
  24388. getIncludes( /*builder*/ ) {
  24389. return this.includes;
  24390. }
  24391. generate( builder ) {
  24392. const includes = this.getIncludes( builder );
  24393. for ( const include of includes ) {
  24394. include.build( builder );
  24395. }
  24396. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  24397. nodeCode.code = this.code;
  24398. return nodeCode.code;
  24399. }
  24400. serialize( data ) {
  24401. super.serialize( data );
  24402. data.code = this.code;
  24403. data.language = this.language;
  24404. }
  24405. deserialize( data ) {
  24406. super.deserialize( data );
  24407. this.code = data.code;
  24408. this.language = data.language;
  24409. }
  24410. }
  24411. /**
  24412. * TSL function for creating a code node.
  24413. *
  24414. * @tsl
  24415. * @function
  24416. * @param {string} [code=''] - The native code.
  24417. * @param {Array<Node>} [includes=[]] - An array of includes.
  24418. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24419. * @returns {CodeNode}
  24420. */
  24421. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  24422. /**
  24423. * TSL function for creating a JS code node.
  24424. *
  24425. * @tsl
  24426. * @function
  24427. * @param {string} src - The native code.
  24428. * @param {Array<Node>} includes - An array of includes.
  24429. * @returns {CodeNode}
  24430. */
  24431. const js = ( src, includes ) => code( src, includes, 'js' );
  24432. /**
  24433. * TSL function for creating a WGSL code node.
  24434. *
  24435. * @tsl
  24436. * @function
  24437. * @param {string} src - The native code.
  24438. * @param {Array<Node>} includes - An array of includes.
  24439. * @returns {CodeNode}
  24440. */
  24441. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  24442. /**
  24443. * TSL function for creating a GLSL code node.
  24444. *
  24445. * @tsl
  24446. * @function
  24447. * @param {string} src - The native code.
  24448. * @param {Array<Node>} includes - An array of includes.
  24449. * @returns {CodeNode}
  24450. */
  24451. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  24452. /**
  24453. * This class represents a native shader function. It can be used to implement
  24454. * certain aspects of a node material with native shader code. There are two predefined
  24455. * TSL functions for easier usage.
  24456. *
  24457. * - `wgslFn`: Creates a WGSL function node.
  24458. * - `glslFn`: Creates a GLSL function node.
  24459. *
  24460. * A basic example with one include looks like so:
  24461. *
  24462. * ```js
  24463. * const desaturateWGSLFn = wgslFn( `
  24464. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  24465. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  24466. * return vec3<f32>( dot( lum, color ) );
  24467. * }`
  24468. *);
  24469. * const someWGSLFn = wgslFn( `
  24470. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  24471. * return desaturate( color );
  24472. * }
  24473. * `, [ desaturateWGSLFn ] );
  24474. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  24475. *```
  24476. * @augments CodeNode
  24477. */
  24478. class FunctionNode extends CodeNode {
  24479. static get type() {
  24480. return 'FunctionNode';
  24481. }
  24482. /**
  24483. * Constructs a new function node.
  24484. *
  24485. * @param {string} [code=''] - The native code.
  24486. * @param {Array<Node>} [includes=[]] - An array of includes.
  24487. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24488. */
  24489. constructor( code = '', includes = [], language = '' ) {
  24490. super( code, includes, language );
  24491. }
  24492. getNodeType( builder ) {
  24493. return this.getNodeFunction( builder ).type;
  24494. }
  24495. /**
  24496. * Returns the inputs of this function node.
  24497. *
  24498. * @param {NodeBuilder} builder - The current node builder.
  24499. * @return {Array<NodeFunctionInput>} The inputs.
  24500. */
  24501. getInputs( builder ) {
  24502. return this.getNodeFunction( builder ).inputs;
  24503. }
  24504. /**
  24505. * Returns the node function for this function node.
  24506. *
  24507. * @param {NodeBuilder} builder - The current node builder.
  24508. * @return {NodeFunction} The node function.
  24509. */
  24510. getNodeFunction( builder ) {
  24511. const nodeData = builder.getDataFromNode( this );
  24512. let nodeFunction = nodeData.nodeFunction;
  24513. if ( nodeFunction === undefined ) {
  24514. nodeFunction = builder.parser.parseFunction( this.code );
  24515. nodeData.nodeFunction = nodeFunction;
  24516. }
  24517. return nodeFunction;
  24518. }
  24519. generate( builder, output ) {
  24520. super.generate( builder );
  24521. const nodeFunction = this.getNodeFunction( builder );
  24522. const name = nodeFunction.name;
  24523. const type = nodeFunction.type;
  24524. const nodeCode = builder.getCodeFromNode( this, type );
  24525. if ( name !== '' ) {
  24526. // use a custom property name
  24527. nodeCode.name = name;
  24528. }
  24529. const propertyName = builder.getPropertyName( nodeCode );
  24530. const code = this.getNodeFunction( builder ).getCode( propertyName );
  24531. nodeCode.code = code + '\n';
  24532. if ( output === 'property' ) {
  24533. return propertyName;
  24534. } else {
  24535. return builder.format( `${ propertyName }()`, type, output );
  24536. }
  24537. }
  24538. }
  24539. const nativeFn = ( code, includes = [], language = '' ) => {
  24540. for ( let i = 0; i < includes.length; i ++ ) {
  24541. const include = includes[ i ];
  24542. // TSL Function: glslFn, wgslFn
  24543. if ( typeof include === 'function' ) {
  24544. includes[ i ] = include.functionNode;
  24545. }
  24546. }
  24547. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  24548. const fn = ( ...params ) => functionNode.call( ...params );
  24549. fn.functionNode = functionNode;
  24550. return fn;
  24551. };
  24552. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  24553. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  24554. /**
  24555. * `ScriptableNode` uses this class to manage script inputs and outputs.
  24556. *
  24557. * @augments Node
  24558. */
  24559. class ScriptableValueNode extends Node {
  24560. static get type() {
  24561. return 'ScriptableValueNode';
  24562. }
  24563. /**
  24564. * Constructs a new scriptable node.
  24565. *
  24566. * @param {any} [value=null] - The value.
  24567. */
  24568. constructor( value = null ) {
  24569. super();
  24570. /**
  24571. * A reference to the value.
  24572. *
  24573. * @private
  24574. * @default null
  24575. */
  24576. this._value = value;
  24577. /**
  24578. * Depending on the type of `_value`, this property might cache parsed data.
  24579. *
  24580. * @private
  24581. * @default null
  24582. */
  24583. this._cache = null;
  24584. /**
  24585. * If this node represents an input, this property represents the input type.
  24586. *
  24587. * @type {?string}
  24588. * @default null
  24589. */
  24590. this.inputType = null;
  24591. /**
  24592. * If this node represents an output, this property represents the output type.
  24593. *
  24594. * @type {?string}
  24595. * @default null
  24596. */
  24597. this.outputType = null;
  24598. /**
  24599. * An event dispatcher for managing events.
  24600. *
  24601. * @type {EventDispatcher}
  24602. */
  24603. this.events = new EventDispatcher();
  24604. /**
  24605. * This flag can be used for type testing.
  24606. *
  24607. * @type {boolean}
  24608. * @readonly
  24609. * @default true
  24610. */
  24611. this.isScriptableValueNode = true;
  24612. }
  24613. /**
  24614. * Whether this node represents an output or not.
  24615. *
  24616. * @type {boolean}
  24617. * @readonly
  24618. * @default true
  24619. */
  24620. get isScriptableOutputNode() {
  24621. return this.outputType !== null;
  24622. }
  24623. set value( val ) {
  24624. if ( this._value === val ) return;
  24625. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  24626. URL.revokeObjectURL( this._cache );
  24627. this._cache = null;
  24628. }
  24629. this._value = val;
  24630. this.events.dispatchEvent( { type: 'change' } );
  24631. this.refresh();
  24632. }
  24633. /**
  24634. * The node's value.
  24635. *
  24636. * @type {any}
  24637. */
  24638. get value() {
  24639. return this._value;
  24640. }
  24641. /**
  24642. * Dispatches the `refresh` event.
  24643. */
  24644. refresh() {
  24645. this.events.dispatchEvent( { type: 'refresh' } );
  24646. }
  24647. /**
  24648. * The `value` property usually represents a node or even binary data in form of array buffers.
  24649. * In this case, this method tries to return the actual value behind the complex type.
  24650. *
  24651. * @return {any} The value.
  24652. */
  24653. getValue() {
  24654. const value = this.value;
  24655. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  24656. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  24657. } else if ( value && value.value !== null && value.value !== undefined && (
  24658. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  24659. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  24660. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  24661. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  24662. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  24663. ( this.inputType === 'Color' && value.value.isColor ) ||
  24664. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  24665. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  24666. ) ) {
  24667. return value.value;
  24668. }
  24669. return this._cache || value;
  24670. }
  24671. /**
  24672. * Overwritten since the node type is inferred from the value.
  24673. *
  24674. * @param {NodeBuilder} builder - The current node builder.
  24675. * @return {string} The node type.
  24676. */
  24677. getNodeType( builder ) {
  24678. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  24679. }
  24680. setup() {
  24681. return this.value && this.value.isNode ? this.value : float();
  24682. }
  24683. serialize( data ) {
  24684. super.serialize( data );
  24685. if ( this.value !== null ) {
  24686. if ( this.inputType === 'ArrayBuffer' ) {
  24687. data.value = arrayBufferToBase64( this.value );
  24688. } else {
  24689. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  24690. }
  24691. } else {
  24692. data.value = null;
  24693. }
  24694. data.inputType = this.inputType;
  24695. data.outputType = this.outputType;
  24696. }
  24697. deserialize( data ) {
  24698. super.deserialize( data );
  24699. let value = null;
  24700. if ( data.value !== null ) {
  24701. if ( data.inputType === 'ArrayBuffer' ) {
  24702. value = base64ToArrayBuffer( data.value );
  24703. } else if ( data.inputType === 'Texture' ) {
  24704. value = data.meta.textures[ data.value ];
  24705. } else {
  24706. value = data.meta.nodes[ data.value ] || null;
  24707. }
  24708. }
  24709. this.value = value;
  24710. this.inputType = data.inputType;
  24711. this.outputType = data.outputType;
  24712. }
  24713. }
  24714. /**
  24715. * TSL function for creating a scriptable value node.
  24716. *
  24717. * @tsl
  24718. * @function
  24719. * @param {any} [value=null] - The value.
  24720. * @returns {ScriptableValueNode}
  24721. */
  24722. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  24723. /**
  24724. * A Map-like data structure for managing resources of scriptable nodes.
  24725. *
  24726. * @augments Map
  24727. */
  24728. class Resources extends Map {
  24729. get( key, callback = null, ...params ) {
  24730. if ( this.has( key ) ) return super.get( key );
  24731. if ( callback !== null ) {
  24732. const value = callback( ...params );
  24733. this.set( key, value );
  24734. return value;
  24735. }
  24736. }
  24737. }
  24738. class Parameters {
  24739. constructor( scriptableNode ) {
  24740. this.scriptableNode = scriptableNode;
  24741. }
  24742. get parameters() {
  24743. return this.scriptableNode.parameters;
  24744. }
  24745. get layout() {
  24746. return this.scriptableNode.getLayout();
  24747. }
  24748. getInputLayout( id ) {
  24749. return this.scriptableNode.getInputLayout( id );
  24750. }
  24751. get( name ) {
  24752. const param = this.parameters[ name ];
  24753. const value = param ? param.getValue() : null;
  24754. return value;
  24755. }
  24756. }
  24757. /**
  24758. * Defines the resources (e.g. namespaces) of scriptable nodes.
  24759. *
  24760. * @type {Resources}
  24761. */
  24762. const ScriptableNodeResources = new Resources();
  24763. /**
  24764. * This type of node allows to implement nodes with custom scripts. The script
  24765. * section is represented as an instance of `CodeNode` written with JavaScript.
  24766. * The script itself must adhere to a specific structure.
  24767. *
  24768. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  24769. * - layout: The layout object defines the script's interface (inputs and outputs).
  24770. *
  24771. * ```js
  24772. * ScriptableNodeResources.set( 'TSL', TSL );
  24773. *
  24774. * const scriptableNode = scriptable( js( `
  24775. * layout = {
  24776. * outputType: 'node',
  24777. * elements: [
  24778. * { name: 'source', inputType: 'node' },
  24779. * ]
  24780. * };
  24781. *
  24782. * const { mul, oscSine } = TSL;
  24783. *
  24784. * function main() {
  24785. * const source = parameters.get( 'source' ) || float();
  24786. * return mul( source, oscSine() ) );
  24787. * }
  24788. *
  24789. * ` ) );
  24790. *
  24791. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  24792. *
  24793. * const material = new THREE.MeshBasicNodeMaterial();
  24794. * material.colorNode = scriptableNode;
  24795. * ```
  24796. *
  24797. * @augments Node
  24798. */
  24799. class ScriptableNode extends Node {
  24800. static get type() {
  24801. return 'ScriptableNode';
  24802. }
  24803. /**
  24804. * Constructs a new scriptable node.
  24805. *
  24806. * @param {?CodeNode} [codeNode=null] - The code node.
  24807. * @param {Object} [parameters={}] - The parameters definition.
  24808. */
  24809. constructor( codeNode = null, parameters = {} ) {
  24810. super();
  24811. /**
  24812. * The code node.
  24813. *
  24814. * @type {?CodeNode}
  24815. * @default null
  24816. */
  24817. this.codeNode = codeNode;
  24818. /**
  24819. * The parameters definition.
  24820. *
  24821. * @type {Object}
  24822. * @default {}
  24823. */
  24824. this.parameters = parameters;
  24825. this._local = new Resources();
  24826. this._output = scriptableValue();
  24827. this._outputs = {};
  24828. this._source = this.source;
  24829. this._method = null;
  24830. this._object = null;
  24831. this._value = null;
  24832. this._needsOutputUpdate = true;
  24833. this.onRefresh = this.onRefresh.bind( this );
  24834. /**
  24835. * This flag can be used for type testing.
  24836. *
  24837. * @type {boolean}
  24838. * @readonly
  24839. * @default true
  24840. */
  24841. this.isScriptableNode = true;
  24842. }
  24843. /**
  24844. * The source code of the scriptable node.
  24845. *
  24846. * @type {string}
  24847. */
  24848. get source() {
  24849. return this.codeNode ? this.codeNode.code : '';
  24850. }
  24851. /**
  24852. * Sets the reference of a local script variable.
  24853. *
  24854. * @param {string} name - The variable name.
  24855. * @param {Object} value - The reference to set.
  24856. * @return {Resources} The resource map
  24857. */
  24858. setLocal( name, value ) {
  24859. return this._local.set( name, value );
  24860. }
  24861. /**
  24862. * Gets the value of a local script variable.
  24863. *
  24864. * @param {string} name - The variable name.
  24865. * @return {Object} The value.
  24866. */
  24867. getLocal( name ) {
  24868. return this._local.get( name );
  24869. }
  24870. /**
  24871. * Event listener for the `refresh` event.
  24872. */
  24873. onRefresh() {
  24874. this._refresh();
  24875. }
  24876. /**
  24877. * Returns an input from the layout with the given id/name.
  24878. *
  24879. * @param {string} id - The id/name of the input.
  24880. * @return {Object} The element entry.
  24881. */
  24882. getInputLayout( id ) {
  24883. for ( const element of this.getLayout() ) {
  24884. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  24885. return element;
  24886. }
  24887. }
  24888. }
  24889. /**
  24890. * Returns an output from the layout with the given id/name.
  24891. *
  24892. * @param {string} id - The id/name of the output.
  24893. * @return {Object} The element entry.
  24894. */
  24895. getOutputLayout( id ) {
  24896. for ( const element of this.getLayout() ) {
  24897. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  24898. return element;
  24899. }
  24900. }
  24901. }
  24902. /**
  24903. * Defines a script output for the given name and value.
  24904. *
  24905. * @param {string} name - The name of the output.
  24906. * @param {Node} value - The node value.
  24907. * @return {ScriptableNode} A reference to this node.
  24908. */
  24909. setOutput( name, value ) {
  24910. const outputs = this._outputs;
  24911. if ( outputs[ name ] === undefined ) {
  24912. outputs[ name ] = scriptableValue( value );
  24913. } else {
  24914. outputs[ name ].value = value;
  24915. }
  24916. return this;
  24917. }
  24918. /**
  24919. * Returns a script output for the given name.
  24920. *
  24921. * @param {string} name - The name of the output.
  24922. * @return {ScriptableValueNode} The node value.
  24923. */
  24924. getOutput( name ) {
  24925. return this._outputs[ name ];
  24926. }
  24927. /**
  24928. * Returns a parameter for the given name
  24929. *
  24930. * @param {string} name - The name of the parameter.
  24931. * @return {ScriptableValueNode} The node value.
  24932. */
  24933. getParameter( name ) {
  24934. return this.parameters[ name ];
  24935. }
  24936. /**
  24937. * Sets a value for the given parameter name.
  24938. *
  24939. * @param {string} name - The parameter name.
  24940. * @param {any} value - The parameter value.
  24941. * @return {ScriptableNode} A reference to this node.
  24942. */
  24943. setParameter( name, value ) {
  24944. const parameters = this.parameters;
  24945. if ( value && value.isScriptableNode ) {
  24946. this.deleteParameter( name );
  24947. parameters[ name ] = value;
  24948. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  24949. } else if ( value && value.isScriptableValueNode ) {
  24950. this.deleteParameter( name );
  24951. parameters[ name ] = value;
  24952. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  24953. } else if ( parameters[ name ] === undefined ) {
  24954. parameters[ name ] = scriptableValue( value );
  24955. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  24956. } else {
  24957. parameters[ name ].value = value;
  24958. }
  24959. return this;
  24960. }
  24961. /**
  24962. * Returns the value of this node which is the value of
  24963. * the default output.
  24964. *
  24965. * @return {Node} The value.
  24966. */
  24967. getValue() {
  24968. return this.getDefaultOutput().getValue();
  24969. }
  24970. /**
  24971. * Deletes a parameter from the script.
  24972. *
  24973. * @param {string} name - The parameter to remove.
  24974. * @return {ScriptableNode} A reference to this node.
  24975. */
  24976. deleteParameter( name ) {
  24977. let valueNode = this.parameters[ name ];
  24978. if ( valueNode ) {
  24979. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  24980. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  24981. }
  24982. return this;
  24983. }
  24984. /**
  24985. * Deletes all parameters from the script.
  24986. *
  24987. * @return {ScriptableNode} A reference to this node.
  24988. */
  24989. clearParameters() {
  24990. for ( const name of Object.keys( this.parameters ) ) {
  24991. this.deleteParameter( name );
  24992. }
  24993. this.needsUpdate = true;
  24994. return this;
  24995. }
  24996. /**
  24997. * Calls a function from the script.
  24998. *
  24999. * @param {string} name - The function name.
  25000. * @param {...any} params - A list of parameters.
  25001. * @return {any} The result of the function call.
  25002. */
  25003. call( name, ...params ) {
  25004. const object = this.getObject();
  25005. const method = object[ name ];
  25006. if ( typeof method === 'function' ) {
  25007. return method( ...params );
  25008. }
  25009. }
  25010. /**
  25011. * Asynchronously calls a function from the script.
  25012. *
  25013. * @param {string} name - The function name.
  25014. * @param {...any} params - A list of parameters.
  25015. * @return {Promise<any>} The result of the function call.
  25016. */
  25017. async callAsync( name, ...params ) {
  25018. const object = this.getObject();
  25019. const method = object[ name ];
  25020. if ( typeof method === 'function' ) {
  25021. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  25022. }
  25023. }
  25024. /**
  25025. * Overwritten since the node types is inferred from the script's output.
  25026. *
  25027. * @param {NodeBuilder} builder - The current node builder
  25028. * @return {string} The node type.
  25029. */
  25030. getNodeType( builder ) {
  25031. return this.getDefaultOutputNode().getNodeType( builder );
  25032. }
  25033. /**
  25034. * Refreshes the script node.
  25035. *
  25036. * @param {?string} [output=null] - An optional output.
  25037. */
  25038. refresh( output = null ) {
  25039. if ( output !== null ) {
  25040. this.getOutput( output ).refresh();
  25041. } else {
  25042. this._refresh();
  25043. }
  25044. }
  25045. /**
  25046. * Returns an object representation of the script.
  25047. *
  25048. * @return {Object} The result object.
  25049. */
  25050. getObject() {
  25051. if ( this.needsUpdate ) this.dispose();
  25052. if ( this._object !== null ) return this._object;
  25053. //
  25054. const refresh = () => this.refresh();
  25055. const setOutput = ( id, value ) => this.setOutput( id, value );
  25056. const parameters = new Parameters( this );
  25057. const THREE = ScriptableNodeResources.get( 'THREE' );
  25058. const TSL = ScriptableNodeResources.get( 'TSL' );
  25059. const method = this.getMethod();
  25060. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  25061. this._object = method( ...params );
  25062. const layout = this._object.layout;
  25063. if ( layout ) {
  25064. if ( layout.cache === false ) {
  25065. this._local.clear();
  25066. }
  25067. // default output
  25068. this._output.outputType = layout.outputType || null;
  25069. if ( Array.isArray( layout.elements ) ) {
  25070. for ( const element of layout.elements ) {
  25071. const id = element.id || element.name;
  25072. if ( element.inputType ) {
  25073. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  25074. this.getParameter( id ).inputType = element.inputType;
  25075. }
  25076. if ( element.outputType ) {
  25077. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  25078. this.getOutput( id ).outputType = element.outputType;
  25079. }
  25080. }
  25081. }
  25082. }
  25083. return this._object;
  25084. }
  25085. deserialize( data ) {
  25086. super.deserialize( data );
  25087. for ( const name in this.parameters ) {
  25088. let valueNode = this.parameters[ name ];
  25089. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25090. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  25091. }
  25092. }
  25093. /**
  25094. * Returns the layout of the script.
  25095. *
  25096. * @return {Object} The script's layout.
  25097. */
  25098. getLayout() {
  25099. return this.getObject().layout;
  25100. }
  25101. /**
  25102. * Returns default node output of the script.
  25103. *
  25104. * @return {Node} The default node output.
  25105. */
  25106. getDefaultOutputNode() {
  25107. const output = this.getDefaultOutput().value;
  25108. if ( output && output.isNode ) {
  25109. return output;
  25110. }
  25111. return float();
  25112. }
  25113. /**
  25114. * Returns default output of the script.
  25115. *
  25116. * @return {ScriptableValueNode} The default output.
  25117. */
  25118. getDefaultOutput() {
  25119. return this._exec()._output;
  25120. }
  25121. /**
  25122. * Returns a function created from the node's script.
  25123. *
  25124. * @return {Function} The function representing the node's code.
  25125. */
  25126. getMethod() {
  25127. if ( this.needsUpdate ) this.dispose();
  25128. if ( this._method !== null ) return this._method;
  25129. //
  25130. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  25131. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  25132. const properties = interfaceProps.join( ', ' );
  25133. const declarations = 'var ' + properties + '; var output = {};\n';
  25134. const returns = '\nreturn { ...output, ' + properties + ' };';
  25135. const code = declarations + this.codeNode.code + returns;
  25136. //
  25137. this._method = new Function( ...parametersProps, code );
  25138. return this._method;
  25139. }
  25140. /**
  25141. * Frees all internal resources.
  25142. */
  25143. dispose() {
  25144. if ( this._method === null ) return;
  25145. if ( this._object && typeof this._object.dispose === 'function' ) {
  25146. this._object.dispose();
  25147. }
  25148. this._method = null;
  25149. this._object = null;
  25150. this._source = null;
  25151. this._value = null;
  25152. this._needsOutputUpdate = true;
  25153. this._output.value = null;
  25154. this._outputs = {};
  25155. }
  25156. setup() {
  25157. return this.getDefaultOutputNode();
  25158. }
  25159. getCacheKey( force ) {
  25160. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  25161. for ( const param in this.parameters ) {
  25162. values.push( this.parameters[ param ].getCacheKey( force ) );
  25163. }
  25164. return hashArray( values );
  25165. }
  25166. set needsUpdate( value ) {
  25167. if ( value === true ) this.dispose();
  25168. }
  25169. get needsUpdate() {
  25170. return this.source !== this._source;
  25171. }
  25172. /**
  25173. * Executes the `main` function of the script.
  25174. *
  25175. * @private
  25176. * @return {ScriptableNode} A reference to this node.
  25177. */
  25178. _exec() {
  25179. if ( this.codeNode === null ) return this;
  25180. if ( this._needsOutputUpdate === true ) {
  25181. this._value = this.call( 'main' );
  25182. this._needsOutputUpdate = false;
  25183. }
  25184. this._output.value = this._value;
  25185. return this;
  25186. }
  25187. /**
  25188. * Executes the refresh.
  25189. *
  25190. * @private
  25191. */
  25192. _refresh() {
  25193. this.needsUpdate = true;
  25194. this._exec();
  25195. this._output.refresh();
  25196. }
  25197. }
  25198. /**
  25199. * TSL function for creating a scriptable node.
  25200. *
  25201. * @tsl
  25202. * @function
  25203. * @param {?CodeNode} [codeNode=null] - The code node.
  25204. * @param {Object} [parameters={}] - The parameters definition.
  25205. * @returns {ScriptableNode}
  25206. */
  25207. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  25208. /**
  25209. * Returns a node that represents the `z` coordinate in view space
  25210. * for the current fragment. It's a different representation of the
  25211. * default depth value.
  25212. *
  25213. * This value can be part of a computation that defines how the fog
  25214. * density increases when moving away from the camera.
  25215. *
  25216. * @param {NodeBuilder} builder - The current node builder.
  25217. * @return {Node} The viewZ node.
  25218. */
  25219. function getViewZNode( builder ) {
  25220. let viewZ;
  25221. const getViewZ = builder.context.getViewZ;
  25222. if ( getViewZ !== undefined ) {
  25223. viewZ = getViewZ( this );
  25224. }
  25225. return ( viewZ || positionView.z ).negate();
  25226. }
  25227. /**
  25228. * Constructs a new range factor node.
  25229. *
  25230. * @tsl
  25231. * @function
  25232. * @param {Node} near - Defines the near value.
  25233. * @param {Node} far - Defines the far value.
  25234. */
  25235. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  25236. const viewZ = getViewZNode( builder );
  25237. return smoothstep( near, far, viewZ );
  25238. } );
  25239. /**
  25240. * Represents an exponential squared fog. This type of fog gives
  25241. * a clear view near the camera and a faster than exponentially
  25242. * densening fog farther from the camera.
  25243. *
  25244. * @tsl
  25245. * @function
  25246. * @param {Node} density - Defines the fog density.
  25247. */
  25248. const densityFogFactor = Fn( ( [ density ], builder ) => {
  25249. const viewZ = getViewZNode( builder );
  25250. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  25251. } );
  25252. /**
  25253. * This class can be used to configure a fog for the scene.
  25254. * Nodes of this type are assigned to `Scene.fogNode`.
  25255. *
  25256. * @tsl
  25257. * @function
  25258. * @param {Node} color - Defines the color of the fog.
  25259. * @param {Node} factor - Defines how the fog is factored in the scene.
  25260. */
  25261. const fog = Fn( ( [ color, factor ] ) => {
  25262. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  25263. } );
  25264. // Deprecated
  25265. /**
  25266. * @tsl
  25267. * @function
  25268. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  25269. *
  25270. * @param {Node} color
  25271. * @param {Node} near
  25272. * @param {Node} far
  25273. * @returns {Function}
  25274. */
  25275. function rangeFog( color, near, far ) { // @deprecated, r171
  25276. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  25277. return fog( color, rangeFogFactor( near, far ) );
  25278. }
  25279. /**
  25280. * @tsl
  25281. * @function
  25282. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  25283. *
  25284. * @param {Node} color
  25285. * @param {Node} density
  25286. * @returns {Function}
  25287. */
  25288. function densityFog( color, density ) { // @deprecated, r171
  25289. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  25290. return fog( color, densityFogFactor( density ) );
  25291. }
  25292. let min = null;
  25293. let max = null;
  25294. /**
  25295. * `RangeNode` generates random instanced attribute data in a defined range.
  25296. * An exemplary use case for this utility node is to generate random per-instance
  25297. * colors:
  25298. * ```js
  25299. * const material = new MeshBasicNodeMaterial();
  25300. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  25301. * const mesh = new InstancedMesh( geometry, material, count );
  25302. * ```
  25303. * @augments Node
  25304. */
  25305. class RangeNode extends Node {
  25306. static get type() {
  25307. return 'RangeNode';
  25308. }
  25309. /**
  25310. * Constructs a new range node.
  25311. *
  25312. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  25313. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  25314. */
  25315. constructor( minNode = float(), maxNode = float() ) {
  25316. super();
  25317. /**
  25318. * A node defining the lower bound of the range.
  25319. *
  25320. * @type {Node<any>}
  25321. * @default float()
  25322. */
  25323. this.minNode = minNode;
  25324. /**
  25325. * A node defining the upper bound of the range.
  25326. *
  25327. * @type {Node<any>}
  25328. * @default float()
  25329. */
  25330. this.maxNode = maxNode;
  25331. }
  25332. /**
  25333. * Returns the vector length which is computed based on the range definition.
  25334. *
  25335. * @param {NodeBuilder} builder - The current node builder.
  25336. * @return {number} The vector length.
  25337. */
  25338. getVectorLength( builder ) {
  25339. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  25340. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  25341. return minLength > maxLength ? minLength : maxLength;
  25342. }
  25343. /**
  25344. * This method is overwritten since the node type is inferred from range definition.
  25345. *
  25346. * @param {NodeBuilder} builder - The current node builder.
  25347. * @return {string} The node type.
  25348. */
  25349. getNodeType( builder ) {
  25350. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  25351. }
  25352. setup( builder ) {
  25353. const object = builder.object;
  25354. let output = null;
  25355. if ( object.count > 1 ) {
  25356. const minValue = this.minNode.value;
  25357. const maxValue = this.maxNode.value;
  25358. const minLength = builder.getTypeLength( getValueType( minValue ) );
  25359. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  25360. min = min || new Vector4();
  25361. max = max || new Vector4();
  25362. min.setScalar( 0 );
  25363. max.setScalar( 0 );
  25364. if ( minLength === 1 ) min.setScalar( minValue );
  25365. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  25366. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  25367. if ( maxLength === 1 ) max.setScalar( maxValue );
  25368. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  25369. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  25370. const stride = 4;
  25371. const length = stride * object.count;
  25372. const array = new Float32Array( length );
  25373. for ( let i = 0; i < length; i ++ ) {
  25374. const index = i % stride;
  25375. const minElementValue = min.getComponent( index );
  25376. const maxElementValue = max.getComponent( index );
  25377. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  25378. }
  25379. const nodeType = this.getNodeType( builder );
  25380. if ( object.count <= 4096 ) {
  25381. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  25382. } else {
  25383. // TODO: Improve anonymous buffer attribute creation removing this part
  25384. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  25385. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  25386. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  25387. }
  25388. } else {
  25389. output = float( 0 );
  25390. }
  25391. return output;
  25392. }
  25393. }
  25394. /**
  25395. * TSL function for creating a range node.
  25396. *
  25397. * @tsl
  25398. * @function
  25399. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  25400. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  25401. * @returns {RangeNode}
  25402. */
  25403. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  25404. /**
  25405. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  25406. * about the currently running dispatch and/or the device it is running on.
  25407. *
  25408. * This node can only be used with a WebGPU backend.
  25409. *
  25410. * @augments Node
  25411. */
  25412. class ComputeBuiltinNode extends Node {
  25413. static get type() {
  25414. return 'ComputeBuiltinNode';
  25415. }
  25416. /**
  25417. * Constructs a new compute builtin node.
  25418. *
  25419. * @param {string} builtinName - The built-in name.
  25420. * @param {string} nodeType - The node type.
  25421. */
  25422. constructor( builtinName, nodeType ) {
  25423. super( nodeType );
  25424. /**
  25425. * The built-in name.
  25426. *
  25427. * @private
  25428. * @type {string}
  25429. */
  25430. this._builtinName = builtinName;
  25431. }
  25432. /**
  25433. * This method is overwritten since hash is derived from the built-in name.
  25434. *
  25435. * @param {NodeBuilder} builder - The current node builder.
  25436. * @return {string} The hash.
  25437. */
  25438. getHash( builder ) {
  25439. return this.getBuiltinName( builder );
  25440. }
  25441. /**
  25442. * This method is overwritten since the node type is simply derived from `nodeType`..
  25443. *
  25444. * @param {NodeBuilder} builder - The current node builder.
  25445. * @return {string} The node type.
  25446. */
  25447. getNodeType( /*builder*/ ) {
  25448. return this.nodeType;
  25449. }
  25450. /**
  25451. * Sets the builtin name.
  25452. *
  25453. * @param {string} builtinName - The built-in name.
  25454. * @return {ComputeBuiltinNode} A reference to this node.
  25455. */
  25456. setBuiltinName( builtinName ) {
  25457. this._builtinName = builtinName;
  25458. return this;
  25459. }
  25460. /**
  25461. * Returns the builtin name.
  25462. *
  25463. * @param {NodeBuilder} builder - The current node builder.
  25464. * @return {string} The builtin name.
  25465. */
  25466. getBuiltinName( /*builder*/ ) {
  25467. return this._builtinName;
  25468. }
  25469. /**
  25470. * Whether the current node builder has the builtin or not.
  25471. *
  25472. * @param {NodeBuilder} builder - The current node builder.
  25473. * @return {boolean} Whether the builder has the builtin or not.
  25474. */
  25475. hasBuiltin( builder ) {
  25476. return builder.hasBuiltin( this._builtinName );
  25477. }
  25478. generate( builder, output ) {
  25479. const builtinName = this.getBuiltinName( builder );
  25480. const nodeType = this.getNodeType( builder );
  25481. if ( builder.shaderStage === 'compute' ) {
  25482. return builder.format( builtinName, nodeType, output );
  25483. } else {
  25484. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  25485. return builder.generateConst( nodeType );
  25486. }
  25487. }
  25488. serialize( data ) {
  25489. super.serialize( data );
  25490. data.global = this.global;
  25491. data._builtinName = this._builtinName;
  25492. }
  25493. deserialize( data ) {
  25494. super.deserialize( data );
  25495. this.global = data.global;
  25496. this._builtinName = data._builtinName;
  25497. }
  25498. }
  25499. /**
  25500. * TSL function for creating a compute builtin node.
  25501. *
  25502. * @tsl
  25503. * @function
  25504. * @param {string} name - The built-in name.
  25505. * @param {string} nodeType - The node type.
  25506. * @returns {ComputeBuiltinNode}
  25507. */
  25508. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  25509. /**
  25510. * Represents the number of workgroups dispatched by the compute shader.
  25511. * ```js
  25512. * // Run 512 invocations/threads with a workgroup size of 128.
  25513. * const computeFn = Fn(() => {
  25514. *
  25515. * // numWorkgroups.x = 4
  25516. * storageBuffer.element(0).assign(numWorkgroups.x)
  25517. *
  25518. * })().compute(512, [128]);
  25519. *
  25520. * // Run 512 invocations/threads with the default workgroup size of 64.
  25521. * const computeFn = Fn(() => {
  25522. *
  25523. * // numWorkgroups.x = 8
  25524. * storageBuffer.element(0).assign(numWorkgroups.x)
  25525. *
  25526. * })().compute(512);
  25527. * ```
  25528. *
  25529. * @tsl
  25530. * @type {ComputeBuiltinNode<uvec3>}
  25531. */
  25532. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  25533. /**
  25534. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  25535. * ```js
  25536. * // Execute 12 compute threads with a workgroup size of 3.
  25537. * const computeFn = Fn( () => {
  25538. *
  25539. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  25540. *
  25541. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  25542. *
  25543. * } ).Else( () => {
  25544. *
  25545. * storageBuffer.element( instanceIndex ).assign( 0 );
  25546. *
  25547. * } );
  25548. *
  25549. * } )().compute( 12, [ 3 ] );
  25550. *
  25551. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  25552. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  25553. * ```
  25554. *
  25555. * @tsl
  25556. * @type {ComputeBuiltinNode<uvec3>}
  25557. */
  25558. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  25559. /**
  25560. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  25561. *
  25562. * @tsl
  25563. * @type {ComputeBuiltinNode<uvec3>}
  25564. */
  25565. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  25566. /**
  25567. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  25568. *
  25569. * @tsl
  25570. * @type {ComputeBuiltinNode<uvec3>}
  25571. */
  25572. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  25573. /**
  25574. * A device dependent variable that exposes the size of the current invocation's subgroup.
  25575. *
  25576. * @tsl
  25577. * @type {ComputeBuiltinNode<uint>}
  25578. */
  25579. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  25580. /**
  25581. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  25582. *
  25583. * This node can only be used with a WebGPU backend.
  25584. *
  25585. * @augments Node
  25586. */
  25587. class BarrierNode extends Node {
  25588. /**
  25589. * Constructs a new barrier node.
  25590. *
  25591. * @param {string} scope - The scope defines the behavior of the node.
  25592. */
  25593. constructor( scope ) {
  25594. super();
  25595. this.scope = scope;
  25596. }
  25597. generate( builder ) {
  25598. const { scope } = this;
  25599. const { renderer } = builder;
  25600. if ( renderer.backend.isWebGLBackend === true ) {
  25601. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  25602. } else {
  25603. builder.addLineFlowCode( `${scope}Barrier()`, this );
  25604. }
  25605. }
  25606. }
  25607. /**
  25608. * TSL function for creating a barrier node.
  25609. *
  25610. * @tsl
  25611. * @function
  25612. * @param {string} scope - The scope defines the behavior of the node..
  25613. * @returns {BarrierNode}
  25614. */
  25615. const barrier = nodeProxy( BarrierNode );
  25616. /**
  25617. * TSL function for creating a workgroup barrier. All compute shader
  25618. * invocations must wait for each invocation within a workgroup to
  25619. * complete before the barrier can be surpassed.
  25620. *
  25621. * @tsl
  25622. * @function
  25623. * @returns {BarrierNode}
  25624. */
  25625. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  25626. /**
  25627. * TSL function for creating a storage barrier. All invocations must
  25628. * wait for each access to variables within the 'storage' address space
  25629. * to complete before the barrier can be passed.
  25630. *
  25631. * @tsl
  25632. * @function
  25633. * @returns {BarrierNode}
  25634. */
  25635. const storageBarrier = () => barrier( 'storage' ).append();
  25636. /**
  25637. * TSL function for creating a texture barrier. All invocations must
  25638. * wait for each access to variables within the 'texture' address space
  25639. * to complete before the barrier can be passed.
  25640. *
  25641. * @tsl
  25642. * @function
  25643. * @returns {BarrierNode}
  25644. */
  25645. const textureBarrier = () => barrier( 'texture' ).append();
  25646. /**
  25647. * Represents an element of a 'workgroup' scoped buffer.
  25648. *
  25649. * @augments ArrayElementNode
  25650. */
  25651. class WorkgroupInfoElementNode extends ArrayElementNode {
  25652. /**
  25653. * Constructs a new workgroup info element node.
  25654. *
  25655. * @param {Node} workgroupInfoNode - The workgroup info node.
  25656. * @param {Node} indexNode - The index node that defines the element access.
  25657. */
  25658. constructor( workgroupInfoNode, indexNode ) {
  25659. super( workgroupInfoNode, indexNode );
  25660. /**
  25661. * This flag can be used for type testing.
  25662. *
  25663. * @type {boolean}
  25664. * @readonly
  25665. * @default true
  25666. */
  25667. this.isWorkgroupInfoElementNode = true;
  25668. }
  25669. generate( builder, output ) {
  25670. let snippet;
  25671. const isAssignContext = builder.context.assign;
  25672. snippet = super.generate( builder );
  25673. if ( isAssignContext !== true ) {
  25674. const type = this.getNodeType( builder );
  25675. snippet = builder.format( snippet, type, output );
  25676. }
  25677. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  25678. return snippet;
  25679. }
  25680. }
  25681. /**
  25682. * A node allowing the user to create a 'workgroup' scoped buffer within the
  25683. * context of a compute shader. Typically, workgroup scoped buffers are
  25684. * created to hold data that is transferred from a global storage scope into
  25685. * a local workgroup scope. For invocations within a workgroup, data
  25686. * access speeds on 'workgroup' scoped buffers can be significantly faster
  25687. * than similar access operations on globally accessible storage buffers.
  25688. *
  25689. * This node can only be used with a WebGPU backend.
  25690. *
  25691. * @augments Node
  25692. */
  25693. class WorkgroupInfoNode extends Node {
  25694. /**
  25695. * Constructs a new buffer scoped to type scope.
  25696. *
  25697. * @param {string} scope - TODO.
  25698. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  25699. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  25700. */
  25701. constructor( scope, bufferType, bufferCount = 0 ) {
  25702. super( bufferType );
  25703. /**
  25704. * The buffer type.
  25705. *
  25706. * @type {string}
  25707. */
  25708. this.bufferType = bufferType;
  25709. /**
  25710. * The buffer count.
  25711. *
  25712. * @type {number}
  25713. * @default 0
  25714. */
  25715. this.bufferCount = bufferCount;
  25716. /**
  25717. * This flag can be used for type testing.
  25718. *
  25719. * @type {boolean}
  25720. * @readonly
  25721. * @default true
  25722. */
  25723. this.isWorkgroupInfoNode = true;
  25724. /**
  25725. * The data type of the array buffer.
  25726. *
  25727. * @type {string}
  25728. */
  25729. this.elementType = bufferType;
  25730. /**
  25731. * TODO.
  25732. *
  25733. * @type {string}
  25734. */
  25735. this.scope = scope;
  25736. }
  25737. /**
  25738. * Sets the name/label of this node.
  25739. *
  25740. * @param {string} name - The name to set.
  25741. * @return {WorkgroupInfoNode} A reference to this node.
  25742. */
  25743. label( name ) {
  25744. this.name = name;
  25745. return this;
  25746. }
  25747. /**
  25748. * Sets the scope of this node.
  25749. *
  25750. * @param {string} scope - The scope to set.
  25751. * @return {WorkgroupInfoNode} A reference to this node.
  25752. */
  25753. setScope( scope ) {
  25754. this.scope = scope;
  25755. return this;
  25756. }
  25757. /**
  25758. * The data type of the array buffer.
  25759. *
  25760. * @return {string} The element type.
  25761. */
  25762. getElementType() {
  25763. return this.elementType;
  25764. }
  25765. /**
  25766. * Overwrites the default implementation since the input type
  25767. * is inferred from the scope.
  25768. *
  25769. * @param {NodeBuilder} builder - The current node builder.
  25770. * @return {string} The input type.
  25771. */
  25772. getInputType( /*builder*/ ) {
  25773. return `${this.scope}Array`;
  25774. }
  25775. /**
  25776. * This method can be used to access elements via an index node.
  25777. *
  25778. * @param {IndexNode} indexNode - indexNode.
  25779. * @return {WorkgroupInfoElementNode} A reference to an element.
  25780. */
  25781. element( indexNode ) {
  25782. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  25783. }
  25784. generate( builder ) {
  25785. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  25786. }
  25787. }
  25788. /**
  25789. * TSL function for creating a workgroup info node.
  25790. * Creates a new 'workgroup' scoped array buffer.
  25791. *
  25792. * @tsl
  25793. * @function
  25794. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  25795. * @param {number} [count=0] - The number of elements in the buffer.
  25796. * @returns {WorkgroupInfoNode}
  25797. */
  25798. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  25799. /**
  25800. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  25801. * within a shader. In an atomic function, any modification to an atomic variable will
  25802. * occur as an indivisible step with a defined order relative to other modifications.
  25803. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  25804. * atomic operations will not interfere with each other.
  25805. *
  25806. * This node can only be used with a WebGPU backend.
  25807. *
  25808. * @augments TempNode
  25809. */
  25810. class AtomicFunctionNode extends TempNode {
  25811. static get type() {
  25812. return 'AtomicFunctionNode';
  25813. }
  25814. /**
  25815. * Constructs a new atomic function node.
  25816. *
  25817. * @param {string} method - The signature of the atomic function to construct.
  25818. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25819. * @param {Node} valueNode - The value that mutates the atomic variable.
  25820. */
  25821. constructor( method, pointerNode, valueNode ) {
  25822. super( 'uint' );
  25823. /**
  25824. * The signature of the atomic function to construct.
  25825. *
  25826. * @type {string}
  25827. */
  25828. this.method = method;
  25829. /**
  25830. * An atomic variable or element of an atomic buffer.
  25831. *
  25832. * @type {Node}
  25833. */
  25834. this.pointerNode = pointerNode;
  25835. /**
  25836. * A value that modifies the atomic variable.
  25837. *
  25838. * @type {Node}
  25839. */
  25840. this.valueNode = valueNode;
  25841. }
  25842. /**
  25843. * Overwrites the default implementation to return the type of
  25844. * the pointer node.
  25845. *
  25846. * @param {NodeBuilder} builder - The current node builder.
  25847. * @return {string} The input type.
  25848. */
  25849. getInputType( builder ) {
  25850. return this.pointerNode.getNodeType( builder );
  25851. }
  25852. /**
  25853. * Overwritten since the node type is inferred from the input type.
  25854. *
  25855. * @param {NodeBuilder} builder - The current node builder.
  25856. * @return {string} The node type.
  25857. */
  25858. getNodeType( builder ) {
  25859. return this.getInputType( builder );
  25860. }
  25861. generate( builder ) {
  25862. const method = this.method;
  25863. const type = this.getNodeType( builder );
  25864. const inputType = this.getInputType( builder );
  25865. const a = this.pointerNode;
  25866. const b = this.valueNode;
  25867. const params = [];
  25868. params.push( `&${ a.build( builder, inputType ) }` );
  25869. if ( b !== null ) {
  25870. params.push( b.build( builder, inputType ) );
  25871. }
  25872. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  25873. if ( b !== null ) {
  25874. builder.addLineFlowCode( methodSnippet, this );
  25875. }
  25876. return methodSnippet;
  25877. }
  25878. }
  25879. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  25880. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  25881. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  25882. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  25883. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  25884. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  25885. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  25886. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  25887. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  25888. /**
  25889. * TSL function for creating an atomic function node.
  25890. *
  25891. * @tsl
  25892. * @function
  25893. * @param {string} method - The signature of the atomic function to construct.
  25894. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25895. * @param {Node} valueNode - The value that mutates the atomic variable.
  25896. * @returns {AtomicFunctionNode}
  25897. */
  25898. const atomicNode = nodeProxy( AtomicFunctionNode );
  25899. /**
  25900. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  25901. *
  25902. * @tsl
  25903. * @function
  25904. * @param {string} method - The signature of the atomic function to construct.
  25905. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25906. * @param {Node} valueNode - The value that mutates the atomic variable.
  25907. * @returns {AtomicFunctionNode}
  25908. */
  25909. const atomicFunc = ( method, pointerNode, valueNode ) => {
  25910. const node = atomicNode( method, pointerNode, valueNode );
  25911. node.append();
  25912. return node;
  25913. };
  25914. /**
  25915. * Loads the value stored in the atomic variable.
  25916. *
  25917. * @tsl
  25918. * @function
  25919. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25920. * @returns {AtomicFunctionNode}
  25921. */
  25922. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  25923. /**
  25924. * Stores a value in the atomic variable.
  25925. *
  25926. * @tsl
  25927. * @function
  25928. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25929. * @param {Node} valueNode - The value that mutates the atomic variable.
  25930. * @returns {AtomicFunctionNode}
  25931. */
  25932. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  25933. /**
  25934. * Increments the value stored in the atomic variable.
  25935. *
  25936. * @tsl
  25937. * @function
  25938. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25939. * @param {Node} valueNode - The value that mutates the atomic variable.
  25940. * @returns {AtomicFunctionNode}
  25941. */
  25942. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  25943. /**
  25944. * Decrements the value stored in the atomic variable.
  25945. *
  25946. * @tsl
  25947. * @function
  25948. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25949. * @param {Node} valueNode - The value that mutates the atomic variable.
  25950. * @returns {AtomicFunctionNode}
  25951. */
  25952. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  25953. /**
  25954. * Stores in an atomic variable the maximum between its current value and a parameter.
  25955. *
  25956. * @tsl
  25957. * @function
  25958. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25959. * @param {Node} valueNode - The value that mutates the atomic variable.
  25960. * @returns {AtomicFunctionNode}
  25961. */
  25962. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  25963. /**
  25964. * Stores in an atomic variable the minimum between its current value and a parameter.
  25965. *
  25966. * @tsl
  25967. * @function
  25968. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25969. * @param {Node} valueNode - The value that mutates the atomic variable.
  25970. * @returns {AtomicFunctionNode}
  25971. */
  25972. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  25973. /**
  25974. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  25975. *
  25976. * @tsl
  25977. * @function
  25978. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25979. * @param {Node} valueNode - The value that mutates the atomic variable.
  25980. * @returns {AtomicFunctionNode}
  25981. */
  25982. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  25983. /**
  25984. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  25985. *
  25986. * @tsl
  25987. * @function
  25988. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25989. * @param {Node} valueNode - The value that mutates the atomic variable.
  25990. * @returns {AtomicFunctionNode}
  25991. */
  25992. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  25993. /**
  25994. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  25995. *
  25996. * @tsl
  25997. * @function
  25998. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  25999. * @param {Node} valueNode - The value that mutates the atomic variable.
  26000. * @returns {AtomicFunctionNode}
  26001. */
  26002. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  26003. let uniformsLib;
  26004. function getLightData( light ) {
  26005. uniformsLib = uniformsLib || new WeakMap();
  26006. let uniforms = uniformsLib.get( light );
  26007. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  26008. return uniforms;
  26009. }
  26010. /**
  26011. * TSL function for getting a shadow matrix uniform node for the given light.
  26012. *
  26013. * @tsl
  26014. * @function
  26015. * @param {Light} light -The light source.
  26016. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  26017. */
  26018. function lightShadowMatrix( light ) {
  26019. const data = getLightData( light );
  26020. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  26021. if ( light.castShadow !== true ) {
  26022. light.shadow.updateMatrices( light );
  26023. }
  26024. return light.shadow.matrix;
  26025. } ) );
  26026. }
  26027. /**
  26028. * TSL function for getting projected uv coordinates for the given light.
  26029. * Relevant when using maps with spot lights.
  26030. *
  26031. * @tsl
  26032. * @function
  26033. * @param {Light} light -The light source.
  26034. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  26035. * @returns {Node<vec3>} The projected uvs.
  26036. */
  26037. function lightProjectionUV( light, position = positionWorld ) {
  26038. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  26039. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  26040. return projectionUV;
  26041. }
  26042. /**
  26043. * TSL function for getting the position in world space for the given light.
  26044. *
  26045. * @tsl
  26046. * @function
  26047. * @param {Light} light -The light source.
  26048. * @returns {UniformNode<vec3>} The light's position in world space.
  26049. */
  26050. function lightPosition( light ) {
  26051. const data = getLightData( light );
  26052. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  26053. }
  26054. /**
  26055. * TSL function for getting the light target position in world space for the given light.
  26056. *
  26057. * @tsl
  26058. * @function
  26059. * @param {Light} light -The light source.
  26060. * @returns {UniformNode<vec3>} The light target position in world space.
  26061. */
  26062. function lightTargetPosition( light ) {
  26063. const data = getLightData( light );
  26064. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  26065. }
  26066. /**
  26067. * TSL function for getting the position in view space for the given light.
  26068. *
  26069. * @tsl
  26070. * @function
  26071. * @param {Light} light - The light source.
  26072. * @returns {UniformNode<vec3>} The light's position in view space.
  26073. */
  26074. function lightViewPosition( light ) {
  26075. const data = getLightData( light );
  26076. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  26077. self.value = self.value || new Vector3();
  26078. self.value.setFromMatrixPosition( light.matrixWorld );
  26079. self.value.applyMatrix4( camera.matrixWorldInverse );
  26080. } ) );
  26081. }
  26082. /**
  26083. * TSL function for getting the light target direction for the given light.
  26084. *
  26085. * @tsl
  26086. * @function
  26087. * @param {Light} light -The light source.
  26088. * @returns {Node<vec3>} The light's target direction.
  26089. */
  26090. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  26091. const sortLights = ( lights ) => {
  26092. return lights.sort( ( a, b ) => a.id - b.id );
  26093. };
  26094. const getLightNodeById = ( id, lightNodes ) => {
  26095. for ( const lightNode of lightNodes ) {
  26096. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26097. return lightNode;
  26098. }
  26099. }
  26100. return null;
  26101. };
  26102. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  26103. /**
  26104. * This node represents the scene's lighting and manages the lighting model's life cycle
  26105. * for the current build 3D object. It is responsible for computing the total outgoing
  26106. * light in a given lighting context.
  26107. *
  26108. * @augments Node
  26109. */
  26110. class LightsNode extends Node {
  26111. static get type() {
  26112. return 'LightsNode';
  26113. }
  26114. /**
  26115. * Constructs a new lights node.
  26116. */
  26117. constructor() {
  26118. super( 'vec3' );
  26119. /**
  26120. * A node representing the total diffuse light.
  26121. *
  26122. * @type {Node<vec3>}
  26123. */
  26124. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  26125. /**
  26126. * A node representing the total specular light.
  26127. *
  26128. * @type {Node<vec3>}
  26129. */
  26130. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  26131. /**
  26132. * A node representing the outgoing light.
  26133. *
  26134. * @type {Node<vec3>}
  26135. */
  26136. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  26137. /**
  26138. * An array representing the lights in the scene.
  26139. *
  26140. * @private
  26141. * @type {Array<Light>}
  26142. */
  26143. this._lights = [];
  26144. /**
  26145. * For each light in the scene, this node will create a
  26146. * corresponding light node.
  26147. *
  26148. * @private
  26149. * @type {?Array<LightingNode>}
  26150. * @default null
  26151. */
  26152. this._lightNodes = null;
  26153. /**
  26154. * A hash for identifying the current light nodes setup.
  26155. *
  26156. * @private
  26157. * @type {?string}
  26158. * @default null
  26159. */
  26160. this._lightNodesHash = null;
  26161. /**
  26162. * `LightsNode` sets this property to `true` by default.
  26163. *
  26164. * @type {boolean}
  26165. * @default true
  26166. */
  26167. this.global = true;
  26168. }
  26169. /**
  26170. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  26171. * light IDs into the cache key.
  26172. *
  26173. * @return {number} The custom cache key.
  26174. */
  26175. customCacheKey() {
  26176. const lightIDs = [];
  26177. const lights = this._lights;
  26178. for ( let i = 0; i < lights.length; i ++ ) {
  26179. lightIDs.push( lights[ i ].id );
  26180. }
  26181. return hashArray( lightIDs );
  26182. }
  26183. /**
  26184. * Computes a hash value for identifying the current light nodes setup.
  26185. *
  26186. * @param {NodeBuilder} builder - A reference to the current node builder.
  26187. * @return {string} The computed hash.
  26188. */
  26189. getHash( builder ) {
  26190. if ( this._lightNodesHash === null ) {
  26191. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26192. const hash = [];
  26193. for ( const lightNode of this._lightNodes ) {
  26194. hash.push( lightNode.getSelf().getHash() );
  26195. }
  26196. this._lightNodesHash = 'lights-' + hash.join( ',' );
  26197. }
  26198. return this._lightNodesHash;
  26199. }
  26200. analyze( builder ) {
  26201. const properties = builder.getDataFromNode( this );
  26202. for ( const node of properties.nodes ) {
  26203. node.build( builder );
  26204. }
  26205. }
  26206. /**
  26207. * Creates lighting nodes for each scene light. This makes it possible to further
  26208. * process lights in the node system.
  26209. *
  26210. * @param {NodeBuilder} builder - A reference to the current node builder.
  26211. */
  26212. setupLightsNode( builder ) {
  26213. const lightNodes = [];
  26214. const previousLightNodes = this._lightNodes;
  26215. const lights = sortLights( this._lights );
  26216. const nodeLibrary = builder.renderer.library;
  26217. for ( const light of lights ) {
  26218. if ( light.isNode ) {
  26219. lightNodes.push( nodeObject( light ) );
  26220. } else {
  26221. let lightNode = null;
  26222. if ( previousLightNodes !== null ) {
  26223. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  26224. }
  26225. if ( lightNode === null ) {
  26226. // find the corresponding node type for a given light
  26227. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  26228. if ( lightNodeClass === null ) {
  26229. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  26230. continue;
  26231. }
  26232. let lightNode = null;
  26233. if ( ! _lightsNodeRef.has( light ) ) {
  26234. lightNode = nodeObject( new lightNodeClass( light ) );
  26235. _lightsNodeRef.set( light, lightNode );
  26236. } else {
  26237. lightNode = _lightsNodeRef.get( light );
  26238. }
  26239. lightNodes.push( lightNode );
  26240. }
  26241. }
  26242. }
  26243. this._lightNodes = lightNodes;
  26244. }
  26245. /**
  26246. * Sets up a direct light in the lighting model.
  26247. *
  26248. * @param {Object} builder - The builder object containing the context and stack.
  26249. * @param {Object} lightNode - The light node.
  26250. * @param {Object} lightData - The light object containing color and direction properties.
  26251. */
  26252. setupDirectLight( builder, lightNode, lightData ) {
  26253. const { lightingModel, reflectedLight } = builder.context;
  26254. lightingModel.direct( {
  26255. ...lightData,
  26256. lightNode,
  26257. reflectedLight
  26258. }, builder );
  26259. }
  26260. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  26261. const { lightingModel, reflectedLight } = builder.context;
  26262. lightingModel.directRectArea( {
  26263. ...lightData,
  26264. lightNode,
  26265. reflectedLight
  26266. }, builder );
  26267. }
  26268. /**
  26269. * Setups the internal lights by building all respective
  26270. * light nodes.
  26271. *
  26272. * @param {NodeBuilder} builder - A reference to the current node builder.
  26273. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  26274. */
  26275. setupLights( builder, lightNodes ) {
  26276. for ( const lightNode of lightNodes ) {
  26277. lightNode.build( builder );
  26278. }
  26279. }
  26280. getLightNodes( builder ) {
  26281. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26282. return this._lightNodes;
  26283. }
  26284. /**
  26285. * The implementation makes sure that for each light in the scene
  26286. * there is a corresponding light node. By building the light nodes
  26287. * and evaluating the lighting model the outgoing light is computed.
  26288. *
  26289. * @param {NodeBuilder} builder - A reference to the current node builder.
  26290. * @return {Node<vec3>} A node representing the outgoing light.
  26291. */
  26292. setup( builder ) {
  26293. const currentLightsNode = builder.lightsNode;
  26294. builder.lightsNode = this;
  26295. //
  26296. let outgoingLightNode = this.outgoingLightNode;
  26297. const context = builder.context;
  26298. const lightingModel = context.lightingModel;
  26299. const properties = builder.getDataFromNode( this );
  26300. if ( lightingModel ) {
  26301. const { totalDiffuseNode, totalSpecularNode } = this;
  26302. context.outgoingLight = outgoingLightNode;
  26303. const stack = builder.addStack();
  26304. //
  26305. properties.nodes = stack.nodes;
  26306. //
  26307. lightingModel.start( builder );
  26308. //
  26309. const { backdrop, backdropAlpha } = context;
  26310. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26311. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26312. if ( backdrop !== null ) {
  26313. if ( backdropAlpha !== null ) {
  26314. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26315. } else {
  26316. totalDiffuse = vec3( backdrop );
  26317. }
  26318. context.material.transparent = true;
  26319. }
  26320. totalDiffuseNode.assign( totalDiffuse );
  26321. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26322. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26323. //
  26324. lightingModel.finish( builder );
  26325. //
  26326. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26327. } else {
  26328. properties.nodes = [];
  26329. }
  26330. //
  26331. builder.lightsNode = currentLightsNode;
  26332. return outgoingLightNode;
  26333. }
  26334. /**
  26335. * Configures this node with an array of lights.
  26336. *
  26337. * @param {Array<Light>} lights - An array of lights.
  26338. * @return {LightsNode} A reference to this node.
  26339. */
  26340. setLights( lights ) {
  26341. this._lights = lights;
  26342. this._lightNodes = null;
  26343. this._lightNodesHash = null;
  26344. return this;
  26345. }
  26346. /**
  26347. * Returns an array of the scene's lights.
  26348. *
  26349. * @return {Array<Light>} The scene's lights.
  26350. */
  26351. getLights() {
  26352. return this._lights;
  26353. }
  26354. /**
  26355. * Whether the scene has lights or not.
  26356. *
  26357. * @type {boolean}
  26358. */
  26359. get hasLights() {
  26360. return this._lights.length > 0;
  26361. }
  26362. }
  26363. /**
  26364. * TSL function for creating an instance of `LightsNode` and configuring
  26365. * it with the given array of lights.
  26366. *
  26367. * @tsl
  26368. * @function
  26369. * @param {Array<Light>} lights - An array of lights.
  26370. * @return {LightsNode} The created lights node.
  26371. */
  26372. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  26373. /**
  26374. * Base class for all shadow nodes.
  26375. *
  26376. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  26377. * Lighting nodes might share the same shadow node type or use specific ones depending on
  26378. * their requirements.
  26379. *
  26380. * @augments Node
  26381. */
  26382. class ShadowBaseNode extends Node {
  26383. static get type() {
  26384. return 'ShadowBaseNode';
  26385. }
  26386. /**
  26387. * Constructs a new shadow base node.
  26388. *
  26389. * @param {Light} light - The shadow casting light.
  26390. */
  26391. constructor( light ) {
  26392. super();
  26393. /**
  26394. * The shadow casting light.
  26395. *
  26396. * @type {Light}
  26397. */
  26398. this.light = light;
  26399. /**
  26400. * Overwritten since shadows are updated by default per render.
  26401. *
  26402. * @type {string}
  26403. * @default 'render'
  26404. */
  26405. this.updateBeforeType = NodeUpdateType.RENDER;
  26406. /**
  26407. * This flag can be used for type testing.
  26408. *
  26409. * @type {boolean}
  26410. * @readonly
  26411. * @default true
  26412. */
  26413. this.isShadowBaseNode = true;
  26414. }
  26415. /**
  26416. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  26417. *
  26418. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  26419. */
  26420. setupShadowPosition( { context, material } ) {
  26421. // Use assign inside an Fn()
  26422. shadowPositionWorld.assign( material.shadowPositionNode || context.shadowPositionWorld || positionWorld );
  26423. }
  26424. /**
  26425. * Can be called when the shadow isn't required anymore. That can happen when
  26426. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  26427. * to `false`.
  26428. */
  26429. dispose() {
  26430. this.updateBeforeType = NodeUpdateType.NONE;
  26431. }
  26432. }
  26433. /**
  26434. * TSL object that represents the vertex position in world space during the shadow pass.
  26435. *
  26436. * @tsl
  26437. * @type {Node<vec3>}
  26438. */
  26439. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  26440. /**
  26441. * Saves the state of the given renderer and stores it into the given state object.
  26442. *
  26443. * If not state object is provided, the function creates one.
  26444. *
  26445. * @function
  26446. * @param {Renderer} renderer - The renderer.
  26447. * @param {Object} [state={}] - The state.
  26448. * @return {Object} The state.
  26449. */
  26450. function saveRendererState( renderer, state = {} ) {
  26451. state.toneMapping = renderer.toneMapping;
  26452. state.toneMappingExposure = renderer.toneMappingExposure;
  26453. state.outputColorSpace = renderer.outputColorSpace;
  26454. state.renderTarget = renderer.getRenderTarget();
  26455. state.activeCubeFace = renderer.getActiveCubeFace();
  26456. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  26457. state.renderObjectFunction = renderer.getRenderObjectFunction();
  26458. state.pixelRatio = renderer.getPixelRatio();
  26459. state.mrt = renderer.getMRT();
  26460. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  26461. state.clearAlpha = renderer.getClearAlpha();
  26462. state.autoClear = renderer.autoClear;
  26463. state.scissorTest = renderer.getScissorTest();
  26464. return state;
  26465. }
  26466. /**
  26467. * Saves the state of the given renderer and stores it into the given state object.
  26468. * Besides, the function also resets the state of the renderer to its default values.
  26469. *
  26470. * If not state object is provided, the function creates one.
  26471. *
  26472. * @function
  26473. * @param {Renderer} renderer - The renderer.
  26474. * @param {Object} [state={}] - The state.
  26475. * @return {Object} The state.
  26476. */
  26477. function resetRendererState( renderer, state ) {
  26478. state = saveRendererState( renderer, state );
  26479. renderer.setMRT( null );
  26480. renderer.setRenderObjectFunction( null );
  26481. renderer.setClearColor( 0x000000, 1 );
  26482. renderer.autoClear = true;
  26483. return state;
  26484. }
  26485. /**
  26486. * Restores the state of the given renderer from the given state object.
  26487. *
  26488. * @function
  26489. * @param {Renderer} renderer - The renderer.
  26490. * @param {Object} state - The state to restore.
  26491. */
  26492. function restoreRendererState( renderer, state ) {
  26493. renderer.toneMapping = state.toneMapping;
  26494. renderer.toneMappingExposure = state.toneMappingExposure;
  26495. renderer.outputColorSpace = state.outputColorSpace;
  26496. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  26497. renderer.setRenderObjectFunction( state.renderObjectFunction );
  26498. renderer.setPixelRatio( state.pixelRatio );
  26499. renderer.setMRT( state.mrt );
  26500. renderer.setClearColor( state.clearColor, state.clearAlpha );
  26501. renderer.autoClear = state.autoClear;
  26502. renderer.setScissorTest( state.scissorTest );
  26503. }
  26504. /**
  26505. * Saves the state of the given scene and stores it into the given state object.
  26506. *
  26507. * If not state object is provided, the function creates one.
  26508. *
  26509. * @function
  26510. * @param {Scene} scene - The scene.
  26511. * @param {Object} [state={}] - The state.
  26512. * @return {Object} The state.
  26513. */
  26514. function saveSceneState( scene, state = {} ) {
  26515. state.background = scene.background;
  26516. state.backgroundNode = scene.backgroundNode;
  26517. state.overrideMaterial = scene.overrideMaterial;
  26518. return state;
  26519. }
  26520. /**
  26521. * Saves the state of the given scene and stores it into the given state object.
  26522. * Besides, the function also resets the state of the scene to its default values.
  26523. *
  26524. * If not state object is provided, the function creates one.
  26525. *
  26526. * @function
  26527. * @param {Scene} scene - The scene.
  26528. * @param {Object} [state={}] - The state.
  26529. * @return {Object} The state.
  26530. */
  26531. function resetSceneState( scene, state ) {
  26532. state = saveSceneState( scene, state );
  26533. scene.background = null;
  26534. scene.backgroundNode = null;
  26535. scene.overrideMaterial = null;
  26536. return state;
  26537. }
  26538. /**
  26539. * Restores the state of the given scene from the given state object.
  26540. *
  26541. * @function
  26542. * @param {Scene} scene - The scene.
  26543. * @param {Object} state - The state to restore.
  26544. */
  26545. function restoreSceneState( scene, state ) {
  26546. scene.background = state.background;
  26547. scene.backgroundNode = state.backgroundNode;
  26548. scene.overrideMaterial = state.overrideMaterial;
  26549. }
  26550. /**
  26551. * Saves the state of the given renderer and scene and stores it into the given state object.
  26552. *
  26553. * If not state object is provided, the function creates one.
  26554. *
  26555. * @function
  26556. * @param {Renderer} renderer - The renderer.
  26557. * @param {Scene} scene - The scene.
  26558. * @param {Object} [state={}] - The state.
  26559. * @return {Object} The state.
  26560. */
  26561. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  26562. state = saveRendererState( renderer, state );
  26563. state = saveSceneState( scene, state );
  26564. return state;
  26565. }
  26566. /**
  26567. * Saves the state of the given renderer and scene and stores it into the given state object.
  26568. * Besides, the function also resets the state of the renderer and scene to its default values.
  26569. *
  26570. * If not state object is provided, the function creates one.
  26571. *
  26572. * @function
  26573. * @param {Renderer} renderer - The renderer.
  26574. * @param {Scene} scene - The scene.
  26575. * @param {Object} [state={}] - The state.
  26576. * @return {Object} The state.
  26577. */
  26578. function resetRendererAndSceneState( renderer, scene, state ) {
  26579. state = resetRendererState( renderer, state );
  26580. state = resetSceneState( scene, state );
  26581. return state;
  26582. }
  26583. /**
  26584. * Restores the state of the given renderer and scene from the given state object.
  26585. *
  26586. * @function
  26587. * @param {Renderer} renderer - The renderer.
  26588. * @param {Scene} scene - The scene.
  26589. * @param {Object} state - The state to restore.
  26590. */
  26591. function restoreRendererAndSceneState( renderer, scene, state ) {
  26592. restoreRendererState( renderer, state );
  26593. restoreSceneState( scene, state );
  26594. }
  26595. var RendererUtils = /*#__PURE__*/Object.freeze({
  26596. __proto__: null,
  26597. resetRendererAndSceneState: resetRendererAndSceneState,
  26598. resetRendererState: resetRendererState,
  26599. resetSceneState: resetSceneState,
  26600. restoreRendererAndSceneState: restoreRendererAndSceneState,
  26601. restoreRendererState: restoreRendererState,
  26602. restoreSceneState: restoreSceneState,
  26603. saveRendererAndSceneState: saveRendererAndSceneState,
  26604. saveRendererState: saveRendererState,
  26605. saveSceneState: saveSceneState
  26606. });
  26607. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  26608. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  26609. let dist = positionWorld.sub( position ).length();
  26610. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  26611. dist = dist.saturate(); // clamp to [ 0, 1 ]
  26612. return dist;
  26613. } );
  26614. const linearShadowDistance = ( light ) => {
  26615. const camera = light.shadow.camera;
  26616. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  26617. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  26618. const referencePosition = objectPosition( light );
  26619. return linearDistance( referencePosition, nearDistance, farDistance );
  26620. };
  26621. const getShadowMaterial = ( light ) => {
  26622. let material = shadowMaterialLib.get( light );
  26623. if ( material === undefined ) {
  26624. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  26625. material = new NodeMaterial();
  26626. material.colorNode = vec4( 0, 0, 0, 1 );
  26627. material.depthNode = depthNode;
  26628. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  26629. material.name = 'ShadowMaterial';
  26630. material.fog = false;
  26631. shadowMaterialLib.set( light, material );
  26632. }
  26633. return material;
  26634. };
  26635. /**
  26636. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  26637. * with a binary `[0,1]` result.
  26638. *
  26639. * @method
  26640. * @param {Object} inputs - The input parameter object.
  26641. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26642. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  26643. * @return {Node<float>} The filtering result.
  26644. */
  26645. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  26646. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  26647. } );
  26648. /**
  26649. * A shadow filtering function performing PCF filtering.
  26650. *
  26651. * @method
  26652. * @param {Object} inputs - The input parameter object.
  26653. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26654. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  26655. * @param {LightShadow} inputs.shadow - The light shadow.
  26656. * @return {Node<float>} The filtering result.
  26657. */
  26658. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  26659. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  26660. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  26661. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  26662. const texelSize = vec2( 1 ).div( mapSize );
  26663. const dx0 = texelSize.x.negate().mul( radius );
  26664. const dy0 = texelSize.y.negate().mul( radius );
  26665. const dx1 = texelSize.x.mul( radius );
  26666. const dy1 = texelSize.y.mul( radius );
  26667. const dx2 = dx0.div( 2 );
  26668. const dy2 = dy0.div( 2 );
  26669. const dx3 = dx1.div( 2 );
  26670. const dy3 = dy1.div( 2 );
  26671. return add(
  26672. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  26673. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  26674. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  26675. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  26676. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  26677. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  26678. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  26679. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  26680. depthCompare( shadowCoord.xy, shadowCoord.z ),
  26681. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  26682. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  26683. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  26684. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  26685. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  26686. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  26687. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  26688. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  26689. ).mul( 1 / 17 );
  26690. } );
  26691. /**
  26692. * A shadow filtering function performing PCF soft filtering.
  26693. *
  26694. * @method
  26695. * @param {Object} inputs - The input parameter object.
  26696. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26697. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  26698. * @param {LightShadow} inputs.shadow - The light shadow.
  26699. * @return {Node<float>} The filtering result.
  26700. */
  26701. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  26702. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  26703. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  26704. const texelSize = vec2( 1 ).div( mapSize );
  26705. const dx = texelSize.x;
  26706. const dy = texelSize.y;
  26707. const uv = shadowCoord.xy;
  26708. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  26709. uv.subAssign( f.mul( texelSize ) );
  26710. return add(
  26711. depthCompare( uv, shadowCoord.z ),
  26712. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  26713. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  26714. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  26715. mix(
  26716. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  26717. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  26718. f.x
  26719. ),
  26720. mix(
  26721. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  26722. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  26723. f.x
  26724. ),
  26725. mix(
  26726. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  26727. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  26728. f.y
  26729. ),
  26730. mix(
  26731. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  26732. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  26733. f.y
  26734. ),
  26735. mix(
  26736. mix(
  26737. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  26738. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  26739. f.x
  26740. ),
  26741. mix(
  26742. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  26743. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  26744. f.x
  26745. ),
  26746. f.y
  26747. )
  26748. ).mul( 1 / 9 );
  26749. } );
  26750. /**
  26751. * A shadow filtering function performing VSM filtering.
  26752. *
  26753. * @method
  26754. * @param {Object} inputs - The input parameter object.
  26755. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26756. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  26757. * @return {Node<float>} The filtering result.
  26758. */
  26759. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  26760. const occlusion = float( 1 ).toVar();
  26761. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  26762. const hardShadow = step( shadowCoord.z, distribution.x );
  26763. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  26764. const distance = shadowCoord.z.sub( distribution.x );
  26765. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  26766. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  26767. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  26768. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  26769. } );
  26770. return occlusion;
  26771. } );
  26772. /**
  26773. * Represents the shader code for the first VSM render pass.
  26774. *
  26775. * @method
  26776. * @param {Object} inputs - The input parameter object.
  26777. * @param {Node<float>} inputs.samples - The number of samples
  26778. * @param {Node<float>} inputs.radius - The radius.
  26779. * @param {Node<float>} inputs.size - The size.
  26780. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  26781. * @return {Node<vec2>} The VSM output.
  26782. */
  26783. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  26784. const mean = float( 0 ).toVar();
  26785. const squaredMean = float( 0 ).toVar();
  26786. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  26787. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  26788. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  26789. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  26790. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  26791. mean.addAssign( depth );
  26792. squaredMean.addAssign( depth.mul( depth ) );
  26793. } );
  26794. mean.divAssign( samples );
  26795. squaredMean.divAssign( samples );
  26796. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  26797. return vec2( mean, std_dev );
  26798. } );
  26799. /**
  26800. * Represents the shader code for the second VSM render pass.
  26801. *
  26802. * @method
  26803. * @param {Object} inputs - The input parameter object.
  26804. * @param {Node<float>} inputs.samples - The number of samples
  26805. * @param {Node<float>} inputs.radius - The radius.
  26806. * @param {Node<float>} inputs.size - The size.
  26807. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  26808. * @return {Node<vec2>} The VSM output.
  26809. */
  26810. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  26811. const mean = float( 0 ).toVar();
  26812. const squaredMean = float( 0 ).toVar();
  26813. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  26814. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  26815. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  26816. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  26817. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  26818. mean.addAssign( distribution.x );
  26819. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  26820. } );
  26821. mean.divAssign( samples );
  26822. squaredMean.divAssign( samples );
  26823. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  26824. return vec2( mean, std_dev );
  26825. } );
  26826. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  26827. //
  26828. let _rendererState;
  26829. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  26830. /**
  26831. * Represents the default shadow implementation for lighting nodes.
  26832. *
  26833. * @augments ShadowBaseNode
  26834. */
  26835. class ShadowNode extends ShadowBaseNode {
  26836. static get type() {
  26837. return 'ShadowNode';
  26838. }
  26839. /**
  26840. * Constructs a new shadow node.
  26841. *
  26842. * @param {Light} light - The shadow casting light.
  26843. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  26844. */
  26845. constructor( light, shadow = null ) {
  26846. super( light );
  26847. /**
  26848. * The light shadow which defines the properties light's
  26849. * shadow.
  26850. *
  26851. * @type {?LightShadow}
  26852. * @default null
  26853. */
  26854. this.shadow = shadow || light.shadow;
  26855. /**
  26856. * A reference to the shadow map which is a render target.
  26857. *
  26858. * @type {?RenderTarget}
  26859. * @default null
  26860. */
  26861. this.shadowMap = null;
  26862. /**
  26863. * Only relevant for VSM shadows. Render target for the
  26864. * first VSM render pass.
  26865. *
  26866. * @type {?RenderTarget}
  26867. * @default null
  26868. */
  26869. this.vsmShadowMapVertical = null;
  26870. /**
  26871. * Only relevant for VSM shadows. Render target for the
  26872. * second VSM render pass.
  26873. *
  26874. * @type {?RenderTarget}
  26875. * @default null
  26876. */
  26877. this.vsmShadowMapHorizontal = null;
  26878. /**
  26879. * Only relevant for VSM shadows. Node material which
  26880. * is used to render the first VSM pass.
  26881. *
  26882. * @type {?NodeMaterial}
  26883. * @default null
  26884. */
  26885. this.vsmMaterialVertical = null;
  26886. /**
  26887. * Only relevant for VSM shadows. Node material which
  26888. * is used to render the second VSM pass.
  26889. *
  26890. * @type {?NodeMaterial}
  26891. * @default null
  26892. */
  26893. this.vsmMaterialHorizontal = null;
  26894. /**
  26895. * A reference to the output node which defines the
  26896. * final result of this shadow node.
  26897. *
  26898. * @type {?Node}
  26899. * @private
  26900. * @default null
  26901. */
  26902. this._node = null;
  26903. this._cameraFrameId = new WeakMap();
  26904. /**
  26905. * This flag can be used for type testing.
  26906. *
  26907. * @type {boolean}
  26908. * @readonly
  26909. * @default true
  26910. */
  26911. this.isShadowNode = true;
  26912. }
  26913. /**
  26914. * Setups the shadow filtering.
  26915. *
  26916. * @param {NodeBuilder} builder - A reference to the current node builder.
  26917. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  26918. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  26919. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  26920. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  26921. * @param {LightShadow} inputs.shadow - The light shadow.
  26922. * @return {Node<float>} The result node of the shadow filtering.
  26923. */
  26924. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  26925. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  26926. .and( shadowCoord.x.lessThanEqual( 1 ) )
  26927. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  26928. .and( shadowCoord.y.lessThanEqual( 1 ) )
  26929. .and( shadowCoord.z.lessThanEqual( 1 ) );
  26930. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  26931. return frustumTest.select( shadowNode, float( 1 ) );
  26932. }
  26933. /**
  26934. * Setups the shadow coordinates.
  26935. *
  26936. * @param {NodeBuilder} builder - A reference to the current node builder.
  26937. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  26938. * @return {Node<vec3>} The shadow coordinates.
  26939. */
  26940. setupShadowCoord( builder, shadowPosition ) {
  26941. const { shadow } = this;
  26942. const { renderer } = builder;
  26943. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  26944. let shadowCoord = shadowPosition;
  26945. let coordZ;
  26946. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  26947. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  26948. coordZ = shadowCoord.z;
  26949. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  26950. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  26951. }
  26952. } else {
  26953. const w = shadowCoord.w;
  26954. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  26955. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  26956. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  26957. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  26958. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  26959. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  26960. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  26961. }
  26962. shadowCoord = vec3(
  26963. shadowCoord.x,
  26964. shadowCoord.y.oneMinus(), // follow webgpu standards
  26965. coordZ.add( bias )
  26966. );
  26967. return shadowCoord;
  26968. }
  26969. /**
  26970. * Returns the shadow filtering function for the given shadow type.
  26971. *
  26972. * @param {number} type - The shadow type.
  26973. * @return {Function} The filtering function.
  26974. */
  26975. getShadowFilterFn( type ) {
  26976. return _shadowFilterLib[ type ];
  26977. }
  26978. /**
  26979. * Setups the shadow output node.
  26980. *
  26981. * @param {NodeBuilder} builder - A reference to the current node builder.
  26982. * @return {Node<vec3>} The shadow output node.
  26983. */
  26984. setupShadow( builder ) {
  26985. const { renderer } = builder;
  26986. const { light, shadow } = this;
  26987. const shadowMapType = renderer.shadowMap.type;
  26988. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  26989. depthTexture.compareFunction = LessCompare;
  26990. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  26991. shadowMap.depthTexture = depthTexture;
  26992. shadow.camera.updateProjectionMatrix();
  26993. // VSM
  26994. if ( shadowMapType === VSMShadowMap ) {
  26995. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  26996. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  26997. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  26998. const shadowPassVertical = texture( depthTexture );
  26999. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  27000. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  27001. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27002. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27003. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  27004. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  27005. material.name = 'VSMVertical';
  27006. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  27007. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  27008. material.name = 'VSMHorizontal';
  27009. }
  27010. //
  27011. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  27012. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  27013. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  27014. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  27015. //
  27016. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  27017. if ( filterFn === null ) {
  27018. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  27019. }
  27020. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  27021. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  27022. const shadowColor = texture( shadowMap.texture, shadowCoord );
  27023. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  27024. this.shadowMap = shadowMap;
  27025. this.shadow.map = shadowMap;
  27026. return shadowOutput;
  27027. }
  27028. /**
  27029. * The implementation performs the setup of the output node. An output is only
  27030. * produces if shadow mapping is globally enabled in the renderer.
  27031. *
  27032. * @param {NodeBuilder} builder - A reference to the current node builder.
  27033. * @return {ShaderCallNodeInternal} The output node.
  27034. */
  27035. setup( builder ) {
  27036. if ( builder.renderer.shadowMap.enabled === false ) return;
  27037. return Fn( () => {
  27038. let node = this._node;
  27039. this.setupShadowPosition( builder );
  27040. if ( node === null ) {
  27041. this._node = node = this.setupShadow( builder );
  27042. }
  27043. if ( builder.material.shadowNode ) { // @deprecated, r171
  27044. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  27045. }
  27046. if ( builder.material.receivedShadowNode ) {
  27047. node = builder.material.receivedShadowNode( node );
  27048. }
  27049. return node;
  27050. } )();
  27051. }
  27052. /**
  27053. * Renders the shadow. The logic of this function could be included
  27054. * into {@link ShadowNode#updateShadow} however more specialized shadow
  27055. * nodes might require a custom shadow map rendering. By having a
  27056. * dedicated method, it's easier to overwrite the default behavior.
  27057. *
  27058. * @param {NodeFrame} frame - A reference to the current node frame.
  27059. */
  27060. renderShadow( frame ) {
  27061. const { shadow, shadowMap, light } = this;
  27062. const { renderer, scene } = frame;
  27063. shadow.updateMatrices( light );
  27064. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  27065. renderer.render( scene, shadow.camera );
  27066. }
  27067. /**
  27068. * Updates the shadow.
  27069. *
  27070. * @param {NodeFrame} frame - A reference to the current node frame.
  27071. */
  27072. updateShadow( frame ) {
  27073. const { shadowMap, light, shadow } = this;
  27074. const { renderer, scene, camera } = frame;
  27075. const shadowType = renderer.shadowMap.type;
  27076. const depthVersion = shadowMap.depthTexture.version;
  27077. this._depthVersionCached = depthVersion;
  27078. shadow.camera.layers.mask = camera.layers.mask;
  27079. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27080. const currentMRT = renderer.getMRT();
  27081. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  27082. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  27083. scene.overrideMaterial = getShadowMaterial( light );
  27084. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  27085. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  27086. if ( useVelocity ) {
  27087. getDataFromObject( object ).useVelocity = true;
  27088. }
  27089. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27090. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  27091. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27092. }
  27093. } );
  27094. renderer.setRenderTarget( shadowMap );
  27095. this.renderShadow( frame );
  27096. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27097. // vsm blur pass
  27098. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  27099. this.vsmPass( renderer );
  27100. }
  27101. restoreRendererAndSceneState( renderer, scene, _rendererState );
  27102. }
  27103. /**
  27104. * For VSM additional render passes are required.
  27105. *
  27106. * @param {Renderer} renderer - A reference to the current renderer.
  27107. */
  27108. vsmPass( renderer ) {
  27109. const { shadow } = this;
  27110. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  27111. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  27112. renderer.setRenderTarget( this.vsmShadowMapVertical );
  27113. _quadMesh.material = this.vsmMaterialVertical;
  27114. _quadMesh.render( renderer );
  27115. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  27116. _quadMesh.material = this.vsmMaterialHorizontal;
  27117. _quadMesh.render( renderer );
  27118. }
  27119. /**
  27120. * Frees the internal resources of this shadow node.
  27121. */
  27122. dispose() {
  27123. this.shadowMap.dispose();
  27124. this.shadowMap = null;
  27125. if ( this.vsmShadowMapVertical !== null ) {
  27126. this.vsmShadowMapVertical.dispose();
  27127. this.vsmShadowMapVertical = null;
  27128. this.vsmMaterialVertical.dispose();
  27129. this.vsmMaterialVertical = null;
  27130. }
  27131. if ( this.vsmShadowMapHorizontal !== null ) {
  27132. this.vsmShadowMapHorizontal.dispose();
  27133. this.vsmShadowMapHorizontal = null;
  27134. this.vsmMaterialHorizontal.dispose();
  27135. this.vsmMaterialHorizontal = null;
  27136. }
  27137. super.dispose();
  27138. }
  27139. /**
  27140. * The implementation performs the update of the shadow map if necessary.
  27141. *
  27142. * @param {NodeFrame} frame - A reference to the current node frame.
  27143. */
  27144. updateBefore( frame ) {
  27145. const { shadow } = this;
  27146. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  27147. if ( needsUpdate ) {
  27148. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  27149. needsUpdate = false;
  27150. }
  27151. this._cameraFrameId[ frame.camera ] = frame.frameId;
  27152. }
  27153. if ( needsUpdate ) {
  27154. this.updateShadow( frame );
  27155. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  27156. shadow.needsUpdate = false;
  27157. }
  27158. }
  27159. }
  27160. }
  27161. /**
  27162. * TSL function for creating an instance of `ShadowNode`.
  27163. *
  27164. * @tsl
  27165. * @function
  27166. * @param {Light} light - The shadow casting light.
  27167. * @param {?LightShadow} [shadow] - The light shadow.
  27168. * @return {ShadowNode} The created shadow node.
  27169. */
  27170. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  27171. const _clearColor$1 = /*@__PURE__*/ new Color();
  27172. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  27173. // vector suitable for 2D texture mapping. This code uses the following layout for the
  27174. // 2D texture:
  27175. //
  27176. // xzXZ
  27177. // y Y
  27178. //
  27179. // Y - Positive y direction
  27180. // y - Negative y direction
  27181. // X - Positive x direction
  27182. // x - Negative x direction
  27183. // Z - Positive z direction
  27184. // z - Negative z direction
  27185. //
  27186. // Source and test bed:
  27187. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  27188. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  27189. const v = pos.toVar();
  27190. // Number of texels to avoid at the edge of each square
  27191. const absV = abs( v );
  27192. // Intersect unit cube
  27193. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  27194. absV.mulAssign( scaleToCube );
  27195. // Apply scale to avoid seams
  27196. // two texels less per square (one texel will do for NEAREST)
  27197. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  27198. // Unwrap
  27199. // space: -1 ... 1 range for each square
  27200. //
  27201. // #X## dim := ( 4 , 2 )
  27202. // # # center := ( 1 , 1 )
  27203. const planar = vec2( v.xy ).toVar();
  27204. const almostATexel = texelSizeY.mul( 1.5 );
  27205. const almostOne = almostATexel.oneMinus();
  27206. If( absV.z.greaterThanEqual( almostOne ), () => {
  27207. If( v.z.greaterThan( 0.0 ), () => {
  27208. planar.x.assign( sub( 4.0, v.x ) );
  27209. } );
  27210. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  27211. const signX = sign( v.x );
  27212. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  27213. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  27214. const signY = sign( v.y );
  27215. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  27216. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  27217. } );
  27218. // Transform to UV space
  27219. // scale := 0.5 / dim
  27220. // translate := ( center + 0.5 ) / dim
  27221. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  27222. } ).setLayout( {
  27223. name: 'cubeToUV',
  27224. type: 'vec2',
  27225. inputs: [
  27226. { name: 'pos', type: 'vec3' },
  27227. { name: 'texelSizeY', type: 'float' }
  27228. ]
  27229. } );
  27230. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  27231. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  27232. } );
  27233. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  27234. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27235. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  27236. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  27237. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  27238. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  27239. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  27240. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  27241. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  27242. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  27243. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  27244. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  27245. .mul( 1.0 / 9.0 );
  27246. } );
  27247. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  27248. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  27249. // the vector from the light to the world-space position of the fragment.
  27250. const lightToPosition = shadowCoord.xyz.toVar();
  27251. const lightToPositionLength = lightToPosition.length();
  27252. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  27253. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  27254. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  27255. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  27256. const result = float( 1.0 ).toVar();
  27257. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  27258. // dp = normalized distance from light to fragment position
  27259. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  27260. dp.addAssign( bias );
  27261. // bd3D = base direction 3D
  27262. const bd3D = lightToPosition.normalize();
  27263. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  27264. // percentage-closer filtering
  27265. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  27266. } );
  27267. return result;
  27268. } );
  27269. const _viewport = /*@__PURE__*/ new Vector4();
  27270. const _viewportSize = /*@__PURE__*/ new Vector2();
  27271. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  27272. /**
  27273. * Represents the shadow implementation for point light nodes.
  27274. *
  27275. * @augments ShadowNode
  27276. */
  27277. class PointShadowNode extends ShadowNode {
  27278. static get type() {
  27279. return 'PointShadowNode';
  27280. }
  27281. /**
  27282. * Constructs a new point shadow node.
  27283. *
  27284. * @param {PointLight} light - The shadow casting point light.
  27285. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  27286. */
  27287. constructor( light, shadow = null ) {
  27288. super( light, shadow );
  27289. }
  27290. /**
  27291. * Overwrites the default implementation to return point light shadow specific
  27292. * filtering functions.
  27293. *
  27294. * @param {number} type - The shadow type.
  27295. * @return {Function} The filtering function.
  27296. */
  27297. getShadowFilterFn( type ) {
  27298. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  27299. }
  27300. /**
  27301. * Overwrites the default implementation so the unaltered shadow position is used.
  27302. *
  27303. * @param {NodeBuilder} builder - A reference to the current node builder.
  27304. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  27305. * @return {Node<vec3>} The shadow coordinates.
  27306. */
  27307. setupShadowCoord( builder, shadowPosition ) {
  27308. return shadowPosition;
  27309. }
  27310. /**
  27311. * Overwrites the default implementation to only use point light specific
  27312. * shadow filter functions.
  27313. *
  27314. * @param {NodeBuilder} builder - A reference to the current node builder.
  27315. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  27316. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  27317. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  27318. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27319. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  27320. * @param {LightShadow} inputs.shadow - The light shadow.
  27321. * @return {Node<float>} The result node of the shadow filtering.
  27322. */
  27323. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  27324. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  27325. }
  27326. /**
  27327. * Overwrites the default implementation with point light specific
  27328. * rendering code.
  27329. *
  27330. * @param {NodeFrame} frame - A reference to the current node frame.
  27331. */
  27332. renderShadow( frame ) {
  27333. const { shadow, shadowMap, light } = this;
  27334. const { renderer, scene } = frame;
  27335. const shadowFrameExtents = shadow.getFrameExtents();
  27336. _shadowMapSize.copy( shadow.mapSize );
  27337. _shadowMapSize.multiply( shadowFrameExtents );
  27338. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  27339. _viewportSize.copy( shadow.mapSize );
  27340. //
  27341. const previousAutoClear = renderer.autoClear;
  27342. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  27343. const previousClearAlpha = renderer.getClearAlpha();
  27344. renderer.autoClear = false;
  27345. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  27346. renderer.clear();
  27347. const viewportCount = shadow.getViewportCount();
  27348. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  27349. const viewport = shadow.getViewport( vp );
  27350. const x = _viewportSize.x * viewport.x;
  27351. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  27352. _viewport.set(
  27353. x,
  27354. y,
  27355. _viewportSize.x * viewport.z,
  27356. _viewportSize.y * viewport.w
  27357. );
  27358. shadowMap.viewport.copy( _viewport );
  27359. shadow.updateMatrices( light, vp );
  27360. renderer.render( scene, shadow.camera );
  27361. }
  27362. //
  27363. renderer.autoClear = previousAutoClear;
  27364. renderer.setClearColor( previousClearColor, previousClearAlpha );
  27365. }
  27366. }
  27367. /**
  27368. * TSL function for creating an instance of `PointShadowNode`.
  27369. *
  27370. * @tsl
  27371. * @function
  27372. * @param {PointLight} light - The shadow casting point light.
  27373. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  27374. * @return {PointShadowNode} The created point shadow node.
  27375. */
  27376. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  27377. /**
  27378. * Base class for analytic light nodes.
  27379. *
  27380. * @augments LightingNode
  27381. */
  27382. class AnalyticLightNode extends LightingNode {
  27383. static get type() {
  27384. return 'AnalyticLightNode';
  27385. }
  27386. /**
  27387. * Constructs a new analytic light node.
  27388. *
  27389. * @param {?Light} [light=null] - The light source.
  27390. */
  27391. constructor( light = null ) {
  27392. super();
  27393. /**
  27394. * The light source.
  27395. *
  27396. * @type {?Light}
  27397. * @default null
  27398. */
  27399. this.light = light;
  27400. /**
  27401. * The light's color value.
  27402. *
  27403. * @type {Color}
  27404. */
  27405. this.color = new Color();
  27406. /**
  27407. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  27408. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  27409. *
  27410. * @type {Node}
  27411. */
  27412. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  27413. /**
  27414. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  27415. * The final color node is represented by a different node when using shadows.
  27416. *
  27417. * @type {?Node}
  27418. * @default null
  27419. */
  27420. this.baseColorNode = null;
  27421. /**
  27422. * Represents the light's shadow.
  27423. *
  27424. * @type {?ShadowNode}
  27425. * @default null
  27426. */
  27427. this.shadowNode = null;
  27428. /**
  27429. * Represents the light's shadow color.
  27430. *
  27431. * @type {?Node}
  27432. * @default null
  27433. */
  27434. this.shadowColorNode = null;
  27435. /**
  27436. * This flag can be used for type testing.
  27437. *
  27438. * @type {boolean}
  27439. * @readonly
  27440. * @default true
  27441. */
  27442. this.isAnalyticLightNode = true;
  27443. /**
  27444. * Overwritten since analytic light nodes are updated
  27445. * once per frame.
  27446. *
  27447. * @type {string}
  27448. * @default 'frame'
  27449. */
  27450. this.updateType = NodeUpdateType.FRAME;
  27451. }
  27452. /**
  27453. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  27454. * `light.id` and `light.castShadow` into the cache key.
  27455. *
  27456. * @return {number} The custom cache key.
  27457. */
  27458. customCacheKey() {
  27459. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  27460. }
  27461. getHash() {
  27462. return this.light.uuid;
  27463. }
  27464. getLightVector( builder ) {
  27465. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  27466. }
  27467. /**
  27468. * Sets up the direct lighting for the analytic light node.
  27469. *
  27470. * @abstract
  27471. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  27472. * @return {Object|undefined} The direct light data (color and direction).
  27473. */
  27474. setupDirect( /*builder*/ ) { }
  27475. /**
  27476. * Sets up the direct rect area lighting for the analytic light node.
  27477. *
  27478. * @abstract
  27479. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  27480. * @return {Object|undefined} The direct rect area light data.
  27481. */
  27482. setupDirectRectArea( /*builder*/ ) { }
  27483. /**
  27484. * Setups the shadow node for this light. The method exists so concrete light classes
  27485. * can setup different types of shadow nodes.
  27486. *
  27487. * @return {ShadowNode} The created shadow node.
  27488. */
  27489. setupShadowNode() {
  27490. return shadow( this.light );
  27491. }
  27492. /**
  27493. * Setups the shadow for this light. This method is only executed if the light
  27494. * cast shadows and the current build object receives shadows. It incorporates
  27495. * shadows into the lighting computation.
  27496. *
  27497. * @param {NodeBuilder} builder - The current node builder.
  27498. */
  27499. setupShadow( builder ) {
  27500. const { renderer } = builder;
  27501. if ( renderer.shadowMap.enabled === false ) return;
  27502. let shadowColorNode = this.shadowColorNode;
  27503. if ( shadowColorNode === null ) {
  27504. const customShadowNode = this.light.shadow.shadowNode;
  27505. let shadowNode;
  27506. if ( customShadowNode !== undefined ) {
  27507. shadowNode = nodeObject( customShadowNode );
  27508. } else {
  27509. shadowNode = this.setupShadowNode();
  27510. }
  27511. this.shadowNode = shadowNode;
  27512. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  27513. this.baseColorNode = this.colorNode;
  27514. }
  27515. //
  27516. this.colorNode = shadowColorNode;
  27517. }
  27518. /**
  27519. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  27520. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  27521. * invocate the respective interface methods.
  27522. *
  27523. * @param {NodeBuilder} builder - The current node builder.
  27524. */
  27525. setup( builder ) {
  27526. this.colorNode = this.baseColorNode || this.colorNode;
  27527. if ( this.light.castShadow ) {
  27528. if ( builder.object.receiveShadow ) {
  27529. this.setupShadow( builder );
  27530. }
  27531. } else if ( this.shadowNode !== null ) {
  27532. this.shadowNode.dispose();
  27533. this.shadowNode = null;
  27534. this.shadowColorNode = null;
  27535. }
  27536. const directLightData = this.setupDirect( builder );
  27537. const directRectAreaLightData = this.setupDirectRectArea( builder );
  27538. if ( directLightData ) {
  27539. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  27540. }
  27541. if ( directRectAreaLightData ) {
  27542. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  27543. }
  27544. }
  27545. /**
  27546. * The update method is used to update light uniforms per frame.
  27547. * Potentially overwritten in concrete light nodes to update light
  27548. * specific uniforms.
  27549. *
  27550. * @param {NodeFrame} frame - A reference to the current node frame.
  27551. */
  27552. update( /*frame*/ ) {
  27553. const { light } = this;
  27554. this.color.copy( light.color ).multiplyScalar( light.intensity );
  27555. }
  27556. }
  27557. /**
  27558. * Represents a `discard` shader operation in TSL.
  27559. *
  27560. * @method
  27561. * @param {Object} inputs - The input parameter object.
  27562. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  27563. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  27564. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  27565. * @return {Node<float>} The distance falloff.
  27566. */
  27567. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  27568. // based upon Frostbite 3 Moving to Physically-based Rendering
  27569. // page 32, equation 26: E[window1]
  27570. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27571. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  27572. return cutoffDistance.greaterThan( 0 ).select(
  27573. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  27574. distanceFalloff
  27575. );
  27576. } ); // validated
  27577. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  27578. const lightDirection = lightVector.normalize();
  27579. const lightDistance = lightVector.length();
  27580. const attenuation = getDistanceAttenuation( {
  27581. lightDistance,
  27582. cutoffDistance,
  27583. decayExponent
  27584. } );
  27585. const lightColor = color.mul( attenuation );
  27586. return { lightDirection, lightColor };
  27587. };
  27588. /**
  27589. * Module for representing point lights as nodes.
  27590. *
  27591. * @augments AnalyticLightNode
  27592. */
  27593. class PointLightNode extends AnalyticLightNode {
  27594. static get type() {
  27595. return 'PointLightNode';
  27596. }
  27597. /**
  27598. * Constructs a new point light node.
  27599. *
  27600. * @param {?PointLight} [light=null] - The point light source.
  27601. */
  27602. constructor( light = null ) {
  27603. super( light );
  27604. /**
  27605. * Uniform node representing the cutoff distance.
  27606. *
  27607. * @type {UniformNode<float>}
  27608. */
  27609. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  27610. /**
  27611. * Uniform node representing the decay exponent.
  27612. *
  27613. * @type {UniformNode<float>}
  27614. */
  27615. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  27616. }
  27617. /**
  27618. * Overwritten to updated point light specific uniforms.
  27619. *
  27620. * @param {NodeFrame} frame - A reference to the current node frame.
  27621. */
  27622. update( frame ) {
  27623. const { light } = this;
  27624. super.update( frame );
  27625. this.cutoffDistanceNode.value = light.distance;
  27626. this.decayExponentNode.value = light.decay;
  27627. }
  27628. /**
  27629. * Overwritten to setup point light specific shadow.
  27630. *
  27631. * @return {PointShadowNode}
  27632. */
  27633. setupShadowNode() {
  27634. return pointShadow( this.light );
  27635. }
  27636. setupDirect( builder ) {
  27637. return directPointLight( {
  27638. color: this.colorNode,
  27639. lightVector: this.getLightVector( builder ),
  27640. cutoffDistance: this.cutoffDistanceNode,
  27641. decayExponent: this.decayExponentNode
  27642. } );
  27643. }
  27644. }
  27645. /**
  27646. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  27647. *
  27648. * @tsl
  27649. * @function
  27650. * @param {Node<vec2>} coord - The uv coordinates.
  27651. * @return {Node<float>} The result data.
  27652. */
  27653. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  27654. const uv = coord.mul( 2.0 );
  27655. const cx = uv.x.floor();
  27656. const cy = uv.y.floor();
  27657. const result = cx.add( cy ).mod( 2.0 );
  27658. return result.sign();
  27659. } );
  27660. /**
  27661. * Generates a circle based on the uv coordinates.
  27662. *
  27663. * @tsl
  27664. * @function
  27665. * @param {Node<vec2>} coord - The uv to generate the circle.
  27666. * @return {Node<float>} The circle shape.
  27667. */
  27668. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  27669. const alpha = float( 1 ).toVar();
  27670. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  27671. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  27672. const dlen = float( len2.fwidth() ).toVar();
  27673. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  27674. } else {
  27675. len2.greaterThan( 1.0 ).discard();
  27676. }
  27677. return alpha;
  27678. } );
  27679. // Three.js Transpiler
  27680. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  27681. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  27682. const f = float( f_immutable ).toVar();
  27683. const t = float( t_immutable ).toVar();
  27684. const b = bool( b_immutable ).toVar();
  27685. return select( b, t, f );
  27686. } ).setLayout( {
  27687. name: 'mx_select',
  27688. type: 'float',
  27689. inputs: [
  27690. { name: 'b', type: 'bool' },
  27691. { name: 't', type: 'float' },
  27692. { name: 'f', type: 'float' }
  27693. ]
  27694. } );
  27695. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  27696. const b = bool( b_immutable ).toVar();
  27697. const val = float( val_immutable ).toVar();
  27698. return select( b, val.negate(), val );
  27699. } ).setLayout( {
  27700. name: 'mx_negate_if',
  27701. type: 'float',
  27702. inputs: [
  27703. { name: 'val', type: 'float' },
  27704. { name: 'b', type: 'bool' }
  27705. ]
  27706. } );
  27707. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  27708. const x = float( x_immutable ).toVar();
  27709. return int( floor( x ) );
  27710. } ).setLayout( {
  27711. name: 'mx_floor',
  27712. type: 'int',
  27713. inputs: [
  27714. { name: 'x', type: 'float' }
  27715. ]
  27716. } );
  27717. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  27718. const x = float( x_immutable ).toVar();
  27719. i.assign( mx_floor( x ) );
  27720. return x.sub( float( i ) );
  27721. } );
  27722. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  27723. const t = float( t_immutable ).toVar();
  27724. const s = float( s_immutable ).toVar();
  27725. const v3 = float( v3_immutable ).toVar();
  27726. const v2 = float( v2_immutable ).toVar();
  27727. const v1 = float( v1_immutable ).toVar();
  27728. const v0 = float( v0_immutable ).toVar();
  27729. const s1 = float( sub( 1.0, s ) ).toVar();
  27730. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  27731. } ).setLayout( {
  27732. name: 'mx_bilerp_0',
  27733. type: 'float',
  27734. inputs: [
  27735. { name: 'v0', type: 'float' },
  27736. { name: 'v1', type: 'float' },
  27737. { name: 'v2', type: 'float' },
  27738. { name: 'v3', type: 'float' },
  27739. { name: 's', type: 'float' },
  27740. { name: 't', type: 'float' }
  27741. ]
  27742. } );
  27743. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  27744. const t = float( t_immutable ).toVar();
  27745. const s = float( s_immutable ).toVar();
  27746. const v3 = vec3( v3_immutable ).toVar();
  27747. const v2 = vec3( v2_immutable ).toVar();
  27748. const v1 = vec3( v1_immutable ).toVar();
  27749. const v0 = vec3( v0_immutable ).toVar();
  27750. const s1 = float( sub( 1.0, s ) ).toVar();
  27751. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  27752. } ).setLayout( {
  27753. name: 'mx_bilerp_1',
  27754. type: 'vec3',
  27755. inputs: [
  27756. { name: 'v0', type: 'vec3' },
  27757. { name: 'v1', type: 'vec3' },
  27758. { name: 'v2', type: 'vec3' },
  27759. { name: 'v3', type: 'vec3' },
  27760. { name: 's', type: 'float' },
  27761. { name: 't', type: 'float' }
  27762. ]
  27763. } );
  27764. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  27765. 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 ] ) => {
  27766. const r = float( r_immutable ).toVar();
  27767. const t = float( t_immutable ).toVar();
  27768. const s = float( s_immutable ).toVar();
  27769. const v7 = float( v7_immutable ).toVar();
  27770. const v6 = float( v6_immutable ).toVar();
  27771. const v5 = float( v5_immutable ).toVar();
  27772. const v4 = float( v4_immutable ).toVar();
  27773. const v3 = float( v3_immutable ).toVar();
  27774. const v2 = float( v2_immutable ).toVar();
  27775. const v1 = float( v1_immutable ).toVar();
  27776. const v0 = float( v0_immutable ).toVar();
  27777. const s1 = float( sub( 1.0, s ) ).toVar();
  27778. const t1 = float( sub( 1.0, t ) ).toVar();
  27779. const r1 = float( sub( 1.0, r ) ).toVar();
  27780. 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 ) ) ) ) ) );
  27781. } ).setLayout( {
  27782. name: 'mx_trilerp_0',
  27783. type: 'float',
  27784. inputs: [
  27785. { name: 'v0', type: 'float' },
  27786. { name: 'v1', type: 'float' },
  27787. { name: 'v2', type: 'float' },
  27788. { name: 'v3', type: 'float' },
  27789. { name: 'v4', type: 'float' },
  27790. { name: 'v5', type: 'float' },
  27791. { name: 'v6', type: 'float' },
  27792. { name: 'v7', type: 'float' },
  27793. { name: 's', type: 'float' },
  27794. { name: 't', type: 'float' },
  27795. { name: 'r', type: 'float' }
  27796. ]
  27797. } );
  27798. 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 ] ) => {
  27799. const r = float( r_immutable ).toVar();
  27800. const t = float( t_immutable ).toVar();
  27801. const s = float( s_immutable ).toVar();
  27802. const v7 = vec3( v7_immutable ).toVar();
  27803. const v6 = vec3( v6_immutable ).toVar();
  27804. const v5 = vec3( v5_immutable ).toVar();
  27805. const v4 = vec3( v4_immutable ).toVar();
  27806. const v3 = vec3( v3_immutable ).toVar();
  27807. const v2 = vec3( v2_immutable ).toVar();
  27808. const v1 = vec3( v1_immutable ).toVar();
  27809. const v0 = vec3( v0_immutable ).toVar();
  27810. const s1 = float( sub( 1.0, s ) ).toVar();
  27811. const t1 = float( sub( 1.0, t ) ).toVar();
  27812. const r1 = float( sub( 1.0, r ) ).toVar();
  27813. 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 ) ) ) ) ) );
  27814. } ).setLayout( {
  27815. name: 'mx_trilerp_1',
  27816. type: 'vec3',
  27817. inputs: [
  27818. { name: 'v0', type: 'vec3' },
  27819. { name: 'v1', type: 'vec3' },
  27820. { name: 'v2', type: 'vec3' },
  27821. { name: 'v3', type: 'vec3' },
  27822. { name: 'v4', type: 'vec3' },
  27823. { name: 'v5', type: 'vec3' },
  27824. { name: 'v6', type: 'vec3' },
  27825. { name: 'v7', type: 'vec3' },
  27826. { name: 's', type: 'float' },
  27827. { name: 't', type: 'float' },
  27828. { name: 'r', type: 'float' }
  27829. ]
  27830. } );
  27831. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  27832. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  27833. const y = float( y_immutable ).toVar();
  27834. const x = float( x_immutable ).toVar();
  27835. const hash = uint( hash_immutable ).toVar();
  27836. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  27837. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  27838. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  27839. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  27840. } ).setLayout( {
  27841. name: 'mx_gradient_float_0',
  27842. type: 'float',
  27843. inputs: [
  27844. { name: 'hash', type: 'uint' },
  27845. { name: 'x', type: 'float' },
  27846. { name: 'y', type: 'float' }
  27847. ]
  27848. } );
  27849. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  27850. const z = float( z_immutable ).toVar();
  27851. const y = float( y_immutable ).toVar();
  27852. const x = float( x_immutable ).toVar();
  27853. const hash = uint( hash_immutable ).toVar();
  27854. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  27855. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  27856. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  27857. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  27858. } ).setLayout( {
  27859. name: 'mx_gradient_float_1',
  27860. type: 'float',
  27861. inputs: [
  27862. { name: 'hash', type: 'uint' },
  27863. { name: 'x', type: 'float' },
  27864. { name: 'y', type: 'float' },
  27865. { name: 'z', type: 'float' }
  27866. ]
  27867. } );
  27868. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  27869. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  27870. const y = float( y_immutable ).toVar();
  27871. const x = float( x_immutable ).toVar();
  27872. const hash = uvec3( hash_immutable ).toVar();
  27873. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  27874. } ).setLayout( {
  27875. name: 'mx_gradient_vec3_0',
  27876. type: 'vec3',
  27877. inputs: [
  27878. { name: 'hash', type: 'uvec3' },
  27879. { name: 'x', type: 'float' },
  27880. { name: 'y', type: 'float' }
  27881. ]
  27882. } );
  27883. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  27884. const z = float( z_immutable ).toVar();
  27885. const y = float( y_immutable ).toVar();
  27886. const x = float( x_immutable ).toVar();
  27887. const hash = uvec3( hash_immutable ).toVar();
  27888. 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 ) );
  27889. } ).setLayout( {
  27890. name: 'mx_gradient_vec3_1',
  27891. type: 'vec3',
  27892. inputs: [
  27893. { name: 'hash', type: 'uvec3' },
  27894. { name: 'x', type: 'float' },
  27895. { name: 'y', type: 'float' },
  27896. { name: 'z', type: 'float' }
  27897. ]
  27898. } );
  27899. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  27900. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27901. const v = float( v_immutable ).toVar();
  27902. return mul( 0.6616, v );
  27903. } ).setLayout( {
  27904. name: 'mx_gradient_scale2d_0',
  27905. type: 'float',
  27906. inputs: [
  27907. { name: 'v', type: 'float' }
  27908. ]
  27909. } );
  27910. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27911. const v = float( v_immutable ).toVar();
  27912. return mul( 0.9820, v );
  27913. } ).setLayout( {
  27914. name: 'mx_gradient_scale3d_0',
  27915. type: 'float',
  27916. inputs: [
  27917. { name: 'v', type: 'float' }
  27918. ]
  27919. } );
  27920. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27921. const v = vec3( v_immutable ).toVar();
  27922. return mul( 0.6616, v );
  27923. } ).setLayout( {
  27924. name: 'mx_gradient_scale2d_1',
  27925. type: 'vec3',
  27926. inputs: [
  27927. { name: 'v', type: 'vec3' }
  27928. ]
  27929. } );
  27930. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  27931. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  27932. const v = vec3( v_immutable ).toVar();
  27933. return mul( 0.9820, v );
  27934. } ).setLayout( {
  27935. name: 'mx_gradient_scale3d_1',
  27936. type: 'vec3',
  27937. inputs: [
  27938. { name: 'v', type: 'vec3' }
  27939. ]
  27940. } );
  27941. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  27942. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  27943. const k = int( k_immutable ).toVar();
  27944. const x = uint( x_immutable ).toVar();
  27945. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  27946. } ).setLayout( {
  27947. name: 'mx_rotl32',
  27948. type: 'uint',
  27949. inputs: [
  27950. { name: 'x', type: 'uint' },
  27951. { name: 'k', type: 'int' }
  27952. ]
  27953. } );
  27954. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  27955. a.subAssign( c );
  27956. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  27957. c.addAssign( b );
  27958. b.subAssign( a );
  27959. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  27960. a.addAssign( c );
  27961. c.subAssign( b );
  27962. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  27963. b.addAssign( a );
  27964. a.subAssign( c );
  27965. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  27966. c.addAssign( b );
  27967. b.subAssign( a );
  27968. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  27969. a.addAssign( c );
  27970. c.subAssign( b );
  27971. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  27972. b.addAssign( a );
  27973. } );
  27974. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  27975. const c = uint( c_immutable ).toVar();
  27976. const b = uint( b_immutable ).toVar();
  27977. const a = uint( a_immutable ).toVar();
  27978. c.bitXorAssign( b );
  27979. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  27980. a.bitXorAssign( c );
  27981. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  27982. b.bitXorAssign( a );
  27983. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  27984. c.bitXorAssign( b );
  27985. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  27986. a.bitXorAssign( c );
  27987. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  27988. b.bitXorAssign( a );
  27989. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  27990. c.bitXorAssign( b );
  27991. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  27992. return c;
  27993. } ).setLayout( {
  27994. name: 'mx_bjfinal',
  27995. type: 'uint',
  27996. inputs: [
  27997. { name: 'a', type: 'uint' },
  27998. { name: 'b', type: 'uint' },
  27999. { name: 'c', type: 'uint' }
  28000. ]
  28001. } );
  28002. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  28003. const bits = uint( bits_immutable ).toVar();
  28004. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  28005. } ).setLayout( {
  28006. name: 'mx_bits_to_01',
  28007. type: 'float',
  28008. inputs: [
  28009. { name: 'bits', type: 'uint' }
  28010. ]
  28011. } );
  28012. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  28013. const t = float( t_immutable ).toVar();
  28014. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  28015. } ).setLayout( {
  28016. name: 'mx_fade',
  28017. type: 'float',
  28018. inputs: [
  28019. { name: 't', type: 'float' }
  28020. ]
  28021. } );
  28022. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28023. const x = int( x_immutable ).toVar();
  28024. const len = uint( uint( 1 ) ).toVar();
  28025. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  28026. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  28027. } ).setLayout( {
  28028. name: 'mx_hash_int_0',
  28029. type: 'uint',
  28030. inputs: [
  28031. { name: 'x', type: 'int' }
  28032. ]
  28033. } );
  28034. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  28035. const y = int( y_immutable ).toVar();
  28036. const x = int( x_immutable ).toVar();
  28037. const len = uint( uint( 2 ) ).toVar();
  28038. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28039. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28040. a.addAssign( uint( x ) );
  28041. b.addAssign( uint( y ) );
  28042. return mx_bjfinal( a, b, c );
  28043. } ).setLayout( {
  28044. name: 'mx_hash_int_1',
  28045. type: 'uint',
  28046. inputs: [
  28047. { name: 'x', type: 'int' },
  28048. { name: 'y', type: 'int' }
  28049. ]
  28050. } );
  28051. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  28052. const z = int( z_immutable ).toVar();
  28053. const y = int( y_immutable ).toVar();
  28054. const x = int( x_immutable ).toVar();
  28055. const len = uint( uint( 3 ) ).toVar();
  28056. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28057. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28058. a.addAssign( uint( x ) );
  28059. b.addAssign( uint( y ) );
  28060. c.addAssign( uint( z ) );
  28061. return mx_bjfinal( a, b, c );
  28062. } ).setLayout( {
  28063. name: 'mx_hash_int_2',
  28064. type: 'uint',
  28065. inputs: [
  28066. { name: 'x', type: 'int' },
  28067. { name: 'y', type: 'int' },
  28068. { name: 'z', type: 'int' }
  28069. ]
  28070. } );
  28071. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  28072. const xx = int( xx_immutable ).toVar();
  28073. const z = int( z_immutable ).toVar();
  28074. const y = int( y_immutable ).toVar();
  28075. const x = int( x_immutable ).toVar();
  28076. const len = uint( uint( 4 ) ).toVar();
  28077. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28078. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28079. a.addAssign( uint( x ) );
  28080. b.addAssign( uint( y ) );
  28081. c.addAssign( uint( z ) );
  28082. mx_bjmix( a, b, c );
  28083. a.addAssign( uint( xx ) );
  28084. return mx_bjfinal( a, b, c );
  28085. } ).setLayout( {
  28086. name: 'mx_hash_int_3',
  28087. type: 'uint',
  28088. inputs: [
  28089. { name: 'x', type: 'int' },
  28090. { name: 'y', type: 'int' },
  28091. { name: 'z', type: 'int' },
  28092. { name: 'xx', type: 'int' }
  28093. ]
  28094. } );
  28095. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  28096. const yy = int( yy_immutable ).toVar();
  28097. const xx = int( xx_immutable ).toVar();
  28098. const z = int( z_immutable ).toVar();
  28099. const y = int( y_immutable ).toVar();
  28100. const x = int( x_immutable ).toVar();
  28101. const len = uint( uint( 5 ) ).toVar();
  28102. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28103. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28104. a.addAssign( uint( x ) );
  28105. b.addAssign( uint( y ) );
  28106. c.addAssign( uint( z ) );
  28107. mx_bjmix( a, b, c );
  28108. a.addAssign( uint( xx ) );
  28109. b.addAssign( uint( yy ) );
  28110. return mx_bjfinal( a, b, c );
  28111. } ).setLayout( {
  28112. name: 'mx_hash_int_4',
  28113. type: 'uint',
  28114. inputs: [
  28115. { name: 'x', type: 'int' },
  28116. { name: 'y', type: 'int' },
  28117. { name: 'z', type: 'int' },
  28118. { name: 'xx', type: 'int' },
  28119. { name: 'yy', type: 'int' }
  28120. ]
  28121. } );
  28122. 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 ] );
  28123. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  28124. const y = int( y_immutable ).toVar();
  28125. const x = int( x_immutable ).toVar();
  28126. const h = uint( mx_hash_int( x, y ) ).toVar();
  28127. const result = uvec3().toVar();
  28128. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  28129. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  28130. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  28131. return result;
  28132. } ).setLayout( {
  28133. name: 'mx_hash_vec3_0',
  28134. type: 'uvec3',
  28135. inputs: [
  28136. { name: 'x', type: 'int' },
  28137. { name: 'y', type: 'int' }
  28138. ]
  28139. } );
  28140. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  28141. const z = int( z_immutable ).toVar();
  28142. const y = int( y_immutable ).toVar();
  28143. const x = int( x_immutable ).toVar();
  28144. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  28145. const result = uvec3().toVar();
  28146. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  28147. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  28148. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  28149. return result;
  28150. } ).setLayout( {
  28151. name: 'mx_hash_vec3_1',
  28152. type: 'uvec3',
  28153. inputs: [
  28154. { name: 'x', type: 'int' },
  28155. { name: 'y', type: 'int' },
  28156. { name: 'z', type: 'int' }
  28157. ]
  28158. } );
  28159. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  28160. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28161. const p = vec2( p_immutable ).toVar();
  28162. const X = int().toVar(), Y = int().toVar();
  28163. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28164. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28165. const u = float( mx_fade( fx ) ).toVar();
  28166. const v = float( mx_fade( fy ) ).toVar();
  28167. 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();
  28168. return mx_gradient_scale2d( result );
  28169. } ).setLayout( {
  28170. name: 'mx_perlin_noise_float_0',
  28171. type: 'float',
  28172. inputs: [
  28173. { name: 'p', type: 'vec2' }
  28174. ]
  28175. } );
  28176. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28177. const p = vec3( p_immutable ).toVar();
  28178. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28179. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28180. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28181. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  28182. const u = float( mx_fade( fx ) ).toVar();
  28183. const v = float( mx_fade( fy ) ).toVar();
  28184. const w = float( mx_fade( fz ) ).toVar();
  28185. 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();
  28186. return mx_gradient_scale3d( result );
  28187. } ).setLayout( {
  28188. name: 'mx_perlin_noise_float_1',
  28189. type: 'float',
  28190. inputs: [
  28191. { name: 'p', type: 'vec3' }
  28192. ]
  28193. } );
  28194. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  28195. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28196. const p = vec2( p_immutable ).toVar();
  28197. const X = int().toVar(), Y = int().toVar();
  28198. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28199. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28200. const u = float( mx_fade( fx ) ).toVar();
  28201. const v = float( mx_fade( fy ) ).toVar();
  28202. 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();
  28203. return mx_gradient_scale2d( result );
  28204. } ).setLayout( {
  28205. name: 'mx_perlin_noise_vec3_0',
  28206. type: 'vec3',
  28207. inputs: [
  28208. { name: 'p', type: 'vec2' }
  28209. ]
  28210. } );
  28211. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28212. const p = vec3( p_immutable ).toVar();
  28213. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28214. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28215. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28216. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  28217. const u = float( mx_fade( fx ) ).toVar();
  28218. const v = float( mx_fade( fy ) ).toVar();
  28219. const w = float( mx_fade( fz ) ).toVar();
  28220. 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();
  28221. return mx_gradient_scale3d( result );
  28222. } ).setLayout( {
  28223. name: 'mx_perlin_noise_vec3_1',
  28224. type: 'vec3',
  28225. inputs: [
  28226. { name: 'p', type: 'vec3' }
  28227. ]
  28228. } );
  28229. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  28230. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28231. const p = float( p_immutable ).toVar();
  28232. const ix = int( mx_floor( p ) ).toVar();
  28233. return mx_bits_to_01( mx_hash_int( ix ) );
  28234. } ).setLayout( {
  28235. name: 'mx_cell_noise_float_0',
  28236. type: 'float',
  28237. inputs: [
  28238. { name: 'p', type: 'float' }
  28239. ]
  28240. } );
  28241. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28242. const p = vec2( p_immutable ).toVar();
  28243. const ix = int( mx_floor( p.x ) ).toVar();
  28244. const iy = int( mx_floor( p.y ) ).toVar();
  28245. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  28246. } ).setLayout( {
  28247. name: 'mx_cell_noise_float_1',
  28248. type: 'float',
  28249. inputs: [
  28250. { name: 'p', type: 'vec2' }
  28251. ]
  28252. } );
  28253. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28254. const p = vec3( p_immutable ).toVar();
  28255. const ix = int( mx_floor( p.x ) ).toVar();
  28256. const iy = int( mx_floor( p.y ) ).toVar();
  28257. const iz = int( mx_floor( p.z ) ).toVar();
  28258. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  28259. } ).setLayout( {
  28260. name: 'mx_cell_noise_float_2',
  28261. type: 'float',
  28262. inputs: [
  28263. { name: 'p', type: 'vec3' }
  28264. ]
  28265. } );
  28266. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28267. const p = vec4( p_immutable ).toVar();
  28268. const ix = int( mx_floor( p.x ) ).toVar();
  28269. const iy = int( mx_floor( p.y ) ).toVar();
  28270. const iz = int( mx_floor( p.z ) ).toVar();
  28271. const iw = int( mx_floor( p.w ) ).toVar();
  28272. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  28273. } ).setLayout( {
  28274. name: 'mx_cell_noise_float_3',
  28275. type: 'float',
  28276. inputs: [
  28277. { name: 'p', type: 'vec4' }
  28278. ]
  28279. } );
  28280. 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 ] );
  28281. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28282. const p = float( p_immutable ).toVar();
  28283. const ix = int( mx_floor( p ) ).toVar();
  28284. 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 ) ) ) );
  28285. } ).setLayout( {
  28286. name: 'mx_cell_noise_vec3_0',
  28287. type: 'vec3',
  28288. inputs: [
  28289. { name: 'p', type: 'float' }
  28290. ]
  28291. } );
  28292. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28293. const p = vec2( p_immutable ).toVar();
  28294. const ix = int( mx_floor( p.x ) ).toVar();
  28295. const iy = int( mx_floor( p.y ) ).toVar();
  28296. 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 ) ) ) );
  28297. } ).setLayout( {
  28298. name: 'mx_cell_noise_vec3_1',
  28299. type: 'vec3',
  28300. inputs: [
  28301. { name: 'p', type: 'vec2' }
  28302. ]
  28303. } );
  28304. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28305. const p = vec3( p_immutable ).toVar();
  28306. const ix = int( mx_floor( p.x ) ).toVar();
  28307. const iy = int( mx_floor( p.y ) ).toVar();
  28308. const iz = int( mx_floor( p.z ) ).toVar();
  28309. 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 ) ) ) );
  28310. } ).setLayout( {
  28311. name: 'mx_cell_noise_vec3_2',
  28312. type: 'vec3',
  28313. inputs: [
  28314. { name: 'p', type: 'vec3' }
  28315. ]
  28316. } );
  28317. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28318. const p = vec4( p_immutable ).toVar();
  28319. const ix = int( mx_floor( p.x ) ).toVar();
  28320. const iy = int( mx_floor( p.y ) ).toVar();
  28321. const iz = int( mx_floor( p.z ) ).toVar();
  28322. const iw = int( mx_floor( p.w ) ).toVar();
  28323. 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 ) ) ) );
  28324. } ).setLayout( {
  28325. name: 'mx_cell_noise_vec3_3',
  28326. type: 'vec3',
  28327. inputs: [
  28328. { name: 'p', type: 'vec4' }
  28329. ]
  28330. } );
  28331. 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 ] );
  28332. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  28333. const diminish = float( diminish_immutable ).toVar();
  28334. const lacunarity = float( lacunarity_immutable ).toVar();
  28335. const octaves = int( octaves_immutable ).toVar();
  28336. const p = vec3( p_immutable ).toVar();
  28337. const result = float( 0.0 ).toVar();
  28338. const amplitude = float( 1.0 ).toVar();
  28339. Loop( octaves, () => {
  28340. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  28341. amplitude.mulAssign( diminish );
  28342. p.mulAssign( lacunarity );
  28343. } );
  28344. return result;
  28345. } ).setLayout( {
  28346. name: 'mx_fractal_noise_float',
  28347. type: 'float',
  28348. inputs: [
  28349. { name: 'p', type: 'vec3' },
  28350. { name: 'octaves', type: 'int' },
  28351. { name: 'lacunarity', type: 'float' },
  28352. { name: 'diminish', type: 'float' }
  28353. ]
  28354. } );
  28355. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  28356. const diminish = float( diminish_immutable ).toVar();
  28357. const lacunarity = float( lacunarity_immutable ).toVar();
  28358. const octaves = int( octaves_immutable ).toVar();
  28359. const p = vec3( p_immutable ).toVar();
  28360. const result = vec3( 0.0 ).toVar();
  28361. const amplitude = float( 1.0 ).toVar();
  28362. Loop( octaves, () => {
  28363. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  28364. amplitude.mulAssign( diminish );
  28365. p.mulAssign( lacunarity );
  28366. } );
  28367. return result;
  28368. } ).setLayout( {
  28369. name: 'mx_fractal_noise_vec3',
  28370. type: 'vec3',
  28371. inputs: [
  28372. { name: 'p', type: 'vec3' },
  28373. { name: 'octaves', type: 'int' },
  28374. { name: 'lacunarity', type: 'float' },
  28375. { name: 'diminish', type: 'float' }
  28376. ]
  28377. } );
  28378. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  28379. const diminish = float( diminish_immutable ).toVar();
  28380. const lacunarity = float( lacunarity_immutable ).toVar();
  28381. const octaves = int( octaves_immutable ).toVar();
  28382. const p = vec3( p_immutable ).toVar();
  28383. 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 ) );
  28384. } ).setLayout( {
  28385. name: 'mx_fractal_noise_vec2',
  28386. type: 'vec2',
  28387. inputs: [
  28388. { name: 'p', type: 'vec3' },
  28389. { name: 'octaves', type: 'int' },
  28390. { name: 'lacunarity', type: 'float' },
  28391. { name: 'diminish', type: 'float' }
  28392. ]
  28393. } );
  28394. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  28395. const diminish = float( diminish_immutable ).toVar();
  28396. const lacunarity = float( lacunarity_immutable ).toVar();
  28397. const octaves = int( octaves_immutable ).toVar();
  28398. const p = vec3( p_immutable ).toVar();
  28399. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  28400. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  28401. return vec4( c, f );
  28402. } ).setLayout( {
  28403. name: 'mx_fractal_noise_vec4',
  28404. type: 'vec4',
  28405. inputs: [
  28406. { name: 'p', type: 'vec3' },
  28407. { name: 'octaves', type: 'int' },
  28408. { name: 'lacunarity', type: 'float' },
  28409. { name: 'diminish', type: 'float' }
  28410. ]
  28411. } );
  28412. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  28413. const metric = int( metric_immutable ).toVar();
  28414. const jitter = float( jitter_immutable ).toVar();
  28415. const yoff = int( yoff_immutable ).toVar();
  28416. const xoff = int( xoff_immutable ).toVar();
  28417. const y = int( y_immutable ).toVar();
  28418. const x = int( x_immutable ).toVar();
  28419. const p = vec2( p_immutable ).toVar();
  28420. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  28421. const off = vec2( tmp.x, tmp.y ).toVar();
  28422. off.subAssign( 0.5 );
  28423. off.mulAssign( jitter );
  28424. off.addAssign( 0.5 );
  28425. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  28426. const diff = vec2( cellpos.sub( p ) ).toVar();
  28427. If( metric.equal( int( 2 ) ), () => {
  28428. return abs( diff.x ).add( abs( diff.y ) );
  28429. } );
  28430. If( metric.equal( int( 3 ) ), () => {
  28431. return max$1( abs( diff.x ), abs( diff.y ) );
  28432. } );
  28433. return dot( diff, diff );
  28434. } ).setLayout( {
  28435. name: 'mx_worley_distance_0',
  28436. type: 'float',
  28437. inputs: [
  28438. { name: 'p', type: 'vec2' },
  28439. { name: 'x', type: 'int' },
  28440. { name: 'y', type: 'int' },
  28441. { name: 'xoff', type: 'int' },
  28442. { name: 'yoff', type: 'int' },
  28443. { name: 'jitter', type: 'float' },
  28444. { name: 'metric', type: 'int' }
  28445. ]
  28446. } );
  28447. 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 ] ) => {
  28448. const metric = int( metric_immutable ).toVar();
  28449. const jitter = float( jitter_immutable ).toVar();
  28450. const zoff = int( zoff_immutable ).toVar();
  28451. const yoff = int( yoff_immutable ).toVar();
  28452. const xoff = int( xoff_immutable ).toVar();
  28453. const z = int( z_immutable ).toVar();
  28454. const y = int( y_immutable ).toVar();
  28455. const x = int( x_immutable ).toVar();
  28456. const p = vec3( p_immutable ).toVar();
  28457. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  28458. off.subAssign( 0.5 );
  28459. off.mulAssign( jitter );
  28460. off.addAssign( 0.5 );
  28461. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  28462. const diff = vec3( cellpos.sub( p ) ).toVar();
  28463. If( metric.equal( int( 2 ) ), () => {
  28464. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  28465. } );
  28466. If( metric.equal( int( 3 ) ), () => {
  28467. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  28468. } );
  28469. return dot( diff, diff );
  28470. } ).setLayout( {
  28471. name: 'mx_worley_distance_1',
  28472. type: 'float',
  28473. inputs: [
  28474. { name: 'p', type: 'vec3' },
  28475. { name: 'x', type: 'int' },
  28476. { name: 'y', type: 'int' },
  28477. { name: 'z', type: 'int' },
  28478. { name: 'xoff', type: 'int' },
  28479. { name: 'yoff', type: 'int' },
  28480. { name: 'zoff', type: 'int' },
  28481. { name: 'jitter', type: 'float' },
  28482. { name: 'metric', type: 'int' }
  28483. ]
  28484. } );
  28485. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  28486. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28487. const metric = int( metric_immutable ).toVar();
  28488. const jitter = float( jitter_immutable ).toVar();
  28489. const p = vec2( p_immutable ).toVar();
  28490. const X = int().toVar(), Y = int().toVar();
  28491. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  28492. const sqdist = float( 1e6 ).toVar();
  28493. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28494. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28495. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  28496. sqdist.assign( min$1( sqdist, dist ) );
  28497. } );
  28498. } );
  28499. If( metric.equal( int( 0 ) ), () => {
  28500. sqdist.assign( sqrt( sqdist ) );
  28501. } );
  28502. return sqdist;
  28503. } ).setLayout( {
  28504. name: 'mx_worley_noise_float_0',
  28505. type: 'float',
  28506. inputs: [
  28507. { name: 'p', type: 'vec2' },
  28508. { name: 'jitter', type: 'float' },
  28509. { name: 'metric', type: 'int' }
  28510. ]
  28511. } );
  28512. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28513. const metric = int( metric_immutable ).toVar();
  28514. const jitter = float( jitter_immutable ).toVar();
  28515. const p = vec2( p_immutable ).toVar();
  28516. const X = int().toVar(), Y = int().toVar();
  28517. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  28518. const sqdist = vec2( 1e6, 1e6 ).toVar();
  28519. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28520. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28521. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  28522. If( dist.lessThan( sqdist.x ), () => {
  28523. sqdist.y.assign( sqdist.x );
  28524. sqdist.x.assign( dist );
  28525. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  28526. sqdist.y.assign( dist );
  28527. } );
  28528. } );
  28529. } );
  28530. If( metric.equal( int( 0 ) ), () => {
  28531. sqdist.assign( sqrt( sqdist ) );
  28532. } );
  28533. return sqdist;
  28534. } ).setLayout( {
  28535. name: 'mx_worley_noise_vec2_0',
  28536. type: 'vec2',
  28537. inputs: [
  28538. { name: 'p', type: 'vec2' },
  28539. { name: 'jitter', type: 'float' },
  28540. { name: 'metric', type: 'int' }
  28541. ]
  28542. } );
  28543. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28544. const metric = int( metric_immutable ).toVar();
  28545. const jitter = float( jitter_immutable ).toVar();
  28546. const p = vec2( p_immutable ).toVar();
  28547. const X = int().toVar(), Y = int().toVar();
  28548. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  28549. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  28550. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28551. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28552. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  28553. If( dist.lessThan( sqdist.x ), () => {
  28554. sqdist.z.assign( sqdist.y );
  28555. sqdist.y.assign( sqdist.x );
  28556. sqdist.x.assign( dist );
  28557. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  28558. sqdist.z.assign( sqdist.y );
  28559. sqdist.y.assign( dist );
  28560. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  28561. sqdist.z.assign( dist );
  28562. } );
  28563. } );
  28564. } );
  28565. If( metric.equal( int( 0 ) ), () => {
  28566. sqdist.assign( sqrt( sqdist ) );
  28567. } );
  28568. return sqdist;
  28569. } ).setLayout( {
  28570. name: 'mx_worley_noise_vec3_0',
  28571. type: 'vec3',
  28572. inputs: [
  28573. { name: 'p', type: 'vec2' },
  28574. { name: 'jitter', type: 'float' },
  28575. { name: 'metric', type: 'int' }
  28576. ]
  28577. } );
  28578. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28579. const metric = int( metric_immutable ).toVar();
  28580. const jitter = float( jitter_immutable ).toVar();
  28581. const p = vec3( p_immutable ).toVar();
  28582. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28583. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  28584. const sqdist = float( 1e6 ).toVar();
  28585. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28586. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28587. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  28588. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  28589. sqdist.assign( min$1( sqdist, dist ) );
  28590. } );
  28591. } );
  28592. } );
  28593. If( metric.equal( int( 0 ) ), () => {
  28594. sqdist.assign( sqrt( sqdist ) );
  28595. } );
  28596. return sqdist;
  28597. } ).setLayout( {
  28598. name: 'mx_worley_noise_float_1',
  28599. type: 'float',
  28600. inputs: [
  28601. { name: 'p', type: 'vec3' },
  28602. { name: 'jitter', type: 'float' },
  28603. { name: 'metric', type: 'int' }
  28604. ]
  28605. } );
  28606. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  28607. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28608. const metric = int( metric_immutable ).toVar();
  28609. const jitter = float( jitter_immutable ).toVar();
  28610. const p = vec3( p_immutable ).toVar();
  28611. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28612. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  28613. const sqdist = vec2( 1e6, 1e6 ).toVar();
  28614. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28615. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28616. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  28617. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  28618. If( dist.lessThan( sqdist.x ), () => {
  28619. sqdist.y.assign( sqdist.x );
  28620. sqdist.x.assign( dist );
  28621. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  28622. sqdist.y.assign( dist );
  28623. } );
  28624. } );
  28625. } );
  28626. } );
  28627. If( metric.equal( int( 0 ) ), () => {
  28628. sqdist.assign( sqrt( sqdist ) );
  28629. } );
  28630. return sqdist;
  28631. } ).setLayout( {
  28632. name: 'mx_worley_noise_vec2_1',
  28633. type: 'vec2',
  28634. inputs: [
  28635. { name: 'p', type: 'vec3' },
  28636. { name: 'jitter', type: 'float' },
  28637. { name: 'metric', type: 'int' }
  28638. ]
  28639. } );
  28640. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  28641. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  28642. const metric = int( metric_immutable ).toVar();
  28643. const jitter = float( jitter_immutable ).toVar();
  28644. const p = vec3( p_immutable ).toVar();
  28645. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28646. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  28647. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  28648. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  28649. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  28650. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  28651. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  28652. If( dist.lessThan( sqdist.x ), () => {
  28653. sqdist.z.assign( sqdist.y );
  28654. sqdist.y.assign( sqdist.x );
  28655. sqdist.x.assign( dist );
  28656. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  28657. sqdist.z.assign( sqdist.y );
  28658. sqdist.y.assign( dist );
  28659. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  28660. sqdist.z.assign( dist );
  28661. } );
  28662. } );
  28663. } );
  28664. } );
  28665. If( metric.equal( int( 0 ) ), () => {
  28666. sqdist.assign( sqrt( sqdist ) );
  28667. } );
  28668. return sqdist;
  28669. } ).setLayout( {
  28670. name: 'mx_worley_noise_vec3_1',
  28671. type: 'vec3',
  28672. inputs: [
  28673. { name: 'p', type: 'vec3' },
  28674. { name: 'jitter', type: 'float' },
  28675. { name: 'metric', type: 'int' }
  28676. ]
  28677. } );
  28678. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  28679. // Three.js Transpiler
  28680. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  28681. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  28682. const s = hsv.y;
  28683. const v = hsv.z;
  28684. const result = vec3().toVar();
  28685. If( s.lessThan( 0.0001 ), () => {
  28686. result.assign( vec3( v, v, v ) );
  28687. } ).Else( () => {
  28688. let h = hsv.x;
  28689. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  28690. const hi = int( trunc( h ) );
  28691. const f = h.sub( float( hi ) );
  28692. const p = v.mul( s.oneMinus() );
  28693. const q = v.mul( s.mul( f ).oneMinus() );
  28694. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  28695. If( hi.equal( int( 0 ) ), () => {
  28696. result.assign( vec3( v, t, p ) );
  28697. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  28698. result.assign( vec3( q, v, p ) );
  28699. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  28700. result.assign( vec3( p, v, t ) );
  28701. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  28702. result.assign( vec3( p, q, v ) );
  28703. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  28704. result.assign( vec3( t, p, v ) );
  28705. } ).Else( () => {
  28706. result.assign( vec3( v, p, q ) );
  28707. } );
  28708. } );
  28709. return result;
  28710. } ).setLayout( {
  28711. name: 'mx_hsvtorgb',
  28712. type: 'vec3',
  28713. inputs: [
  28714. { name: 'hsv', type: 'vec3' }
  28715. ]
  28716. } );
  28717. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  28718. const c = vec3( c_immutable ).toVar();
  28719. const r = float( c.x ).toVar();
  28720. const g = float( c.y ).toVar();
  28721. const b = float( c.z ).toVar();
  28722. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  28723. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  28724. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  28725. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  28726. v.assign( maxcomp );
  28727. If( maxcomp.greaterThan( 0.0 ), () => {
  28728. s.assign( delta.div( maxcomp ) );
  28729. } ).Else( () => {
  28730. s.assign( 0.0 );
  28731. } );
  28732. If( s.lessThanEqual( 0.0 ), () => {
  28733. h.assign( 0.0 );
  28734. } ).Else( () => {
  28735. If( r.greaterThanEqual( maxcomp ), () => {
  28736. h.assign( g.sub( b ).div( delta ) );
  28737. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  28738. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  28739. } ).Else( () => {
  28740. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  28741. } );
  28742. h.mulAssign( 1.0 / 6.0 );
  28743. If( h.lessThan( 0.0 ), () => {
  28744. h.addAssign( 1.0 );
  28745. } );
  28746. } );
  28747. return vec3( h, s, v );
  28748. } ).setLayout( {
  28749. name: 'mx_rgbtohsv',
  28750. type: 'vec3',
  28751. inputs: [
  28752. { name: 'c', type: 'vec3' }
  28753. ]
  28754. } );
  28755. // Three.js Transpiler
  28756. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  28757. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  28758. const color = vec3( color_immutable ).toVar();
  28759. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  28760. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  28761. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  28762. return mix( linSeg, powSeg, isAbove );
  28763. } ).setLayout( {
  28764. name: 'mx_srgb_texture_to_lin_rec709',
  28765. type: 'vec3',
  28766. inputs: [
  28767. { name: 'color', type: 'vec3' }
  28768. ]
  28769. } );
  28770. const mx_aastep = ( threshold, value ) => {
  28771. threshold = float( threshold );
  28772. value = float( value );
  28773. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  28774. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  28775. };
  28776. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  28777. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  28778. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  28779. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  28780. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  28781. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  28782. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  28783. const mx_safepower = ( in1, in2 = 1 ) => {
  28784. in1 = float( in1 );
  28785. return in1.abs().pow( in2 ).mul( in1.sign() );
  28786. };
  28787. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  28788. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  28789. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  28790. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  28791. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  28792. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  28793. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  28794. return noise_vec4.mul( amplitude ).add( pivot );
  28795. };
  28796. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  28797. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  28798. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  28799. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  28800. 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 );
  28801. 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 );
  28802. 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 );
  28803. 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 );
  28804. /**
  28805. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  28806. *
  28807. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  28808. *
  28809. * ```js
  28810. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  28811. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  28812. * ```
  28813. *
  28814. * @tsl
  28815. * @function
  28816. * @param {Node<vec3>} normal - The normal to correct.
  28817. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  28818. * @param {Node<vec3>} cubePos - The cube position.
  28819. * @return {Node<vec3>} The parallax corrected normal.
  28820. */
  28821. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  28822. const nDir = normalize( normal ).toVar( 'nDir' );
  28823. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  28824. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  28825. const rbminmax = vec3().toVar( 'rbminmax' );
  28826. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  28827. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  28828. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  28829. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  28830. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  28831. return boxIntersection.sub( cubePos );
  28832. } );
  28833. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  28834. // normal is assumed to have unit length
  28835. const x = normal.x, y = normal.y, z = normal.z;
  28836. // band 0
  28837. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  28838. // band 1
  28839. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  28840. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  28841. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  28842. // band 2
  28843. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  28844. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  28845. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  28846. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  28847. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  28848. return result;
  28849. } );
  28850. // constants
  28851. var TSL = /*#__PURE__*/Object.freeze({
  28852. __proto__: null,
  28853. BRDF_GGX: BRDF_GGX,
  28854. BRDF_Lambert: BRDF_Lambert,
  28855. BasicPointShadowFilter: BasicPointShadowFilter,
  28856. BasicShadowFilter: BasicShadowFilter,
  28857. Break: Break,
  28858. Const: Const,
  28859. Continue: Continue,
  28860. DFGApprox: DFGApprox,
  28861. D_GGX: D_GGX,
  28862. Discard: Discard,
  28863. EPSILON: EPSILON,
  28864. F_Schlick: F_Schlick,
  28865. Fn: Fn,
  28866. INFINITY: INFINITY,
  28867. If: If,
  28868. Loop: Loop,
  28869. NodeAccess: NodeAccess,
  28870. NodeShaderStage: NodeShaderStage,
  28871. NodeType: NodeType,
  28872. NodeUpdateType: NodeUpdateType,
  28873. PCFShadowFilter: PCFShadowFilter,
  28874. PCFSoftShadowFilter: PCFSoftShadowFilter,
  28875. PI: PI,
  28876. PI2: PI2,
  28877. PointShadowFilter: PointShadowFilter,
  28878. Return: Return,
  28879. Schlick_to_F0: Schlick_to_F0,
  28880. ScriptableNodeResources: ScriptableNodeResources,
  28881. ShaderNode: ShaderNode,
  28882. TBNViewMatrix: TBNViewMatrix,
  28883. VSMShadowFilter: VSMShadowFilter,
  28884. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  28885. Var: Var,
  28886. abs: abs,
  28887. acesFilmicToneMapping: acesFilmicToneMapping,
  28888. acos: acos,
  28889. add: add,
  28890. addMethodChaining: addMethodChaining,
  28891. addNodeElement: addNodeElement,
  28892. agxToneMapping: agxToneMapping,
  28893. all: all,
  28894. alphaT: alphaT,
  28895. and: and,
  28896. anisotropy: anisotropy,
  28897. anisotropyB: anisotropyB,
  28898. anisotropyT: anisotropyT,
  28899. any: any,
  28900. append: append,
  28901. array: array,
  28902. arrayBuffer: arrayBuffer,
  28903. asin: asin,
  28904. assign: assign,
  28905. atan: atan,
  28906. atan2: atan2,
  28907. atomicAdd: atomicAdd,
  28908. atomicAnd: atomicAnd,
  28909. atomicFunc: atomicFunc,
  28910. atomicLoad: atomicLoad,
  28911. atomicMax: atomicMax,
  28912. atomicMin: atomicMin,
  28913. atomicOr: atomicOr,
  28914. atomicStore: atomicStore,
  28915. atomicSub: atomicSub,
  28916. atomicXor: atomicXor,
  28917. attenuationColor: attenuationColor,
  28918. attenuationDistance: attenuationDistance,
  28919. attribute: attribute,
  28920. attributeArray: attributeArray,
  28921. backgroundBlurriness: backgroundBlurriness,
  28922. backgroundIntensity: backgroundIntensity,
  28923. backgroundRotation: backgroundRotation,
  28924. batch: batch,
  28925. billboarding: billboarding,
  28926. bitAnd: bitAnd,
  28927. bitNot: bitNot,
  28928. bitOr: bitOr,
  28929. bitXor: bitXor,
  28930. bitangentGeometry: bitangentGeometry,
  28931. bitangentLocal: bitangentLocal,
  28932. bitangentView: bitangentView,
  28933. bitangentWorld: bitangentWorld,
  28934. bitcast: bitcast,
  28935. blendBurn: blendBurn,
  28936. blendColor: blendColor,
  28937. blendDodge: blendDodge,
  28938. blendOverlay: blendOverlay,
  28939. blendScreen: blendScreen,
  28940. blur: blur,
  28941. bool: bool,
  28942. buffer: buffer,
  28943. bufferAttribute: bufferAttribute,
  28944. bumpMap: bumpMap,
  28945. burn: burn,
  28946. bvec2: bvec2,
  28947. bvec3: bvec3,
  28948. bvec4: bvec4,
  28949. bypass: bypass,
  28950. cache: cache,
  28951. call: call,
  28952. cameraFar: cameraFar,
  28953. cameraIndex: cameraIndex,
  28954. cameraNear: cameraNear,
  28955. cameraNormalMatrix: cameraNormalMatrix,
  28956. cameraPosition: cameraPosition,
  28957. cameraProjectionMatrix: cameraProjectionMatrix,
  28958. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  28959. cameraViewMatrix: cameraViewMatrix,
  28960. cameraWorldMatrix: cameraWorldMatrix,
  28961. cbrt: cbrt,
  28962. cdl: cdl,
  28963. ceil: ceil,
  28964. checker: checker,
  28965. cineonToneMapping: cineonToneMapping,
  28966. clamp: clamp,
  28967. clearcoat: clearcoat,
  28968. clearcoatRoughness: clearcoatRoughness,
  28969. code: code,
  28970. color: color,
  28971. colorSpaceToWorking: colorSpaceToWorking,
  28972. colorToDirection: colorToDirection,
  28973. compute: compute,
  28974. cond: cond,
  28975. context: context,
  28976. convert: convert,
  28977. convertColorSpace: convertColorSpace,
  28978. convertToTexture: convertToTexture,
  28979. cos: cos,
  28980. cross: cross,
  28981. cubeTexture: cubeTexture,
  28982. cubeToUV: cubeToUV,
  28983. dFdx: dFdx,
  28984. dFdy: dFdy,
  28985. dashSize: dashSize,
  28986. defaultBuildStages: defaultBuildStages,
  28987. defaultShaderStages: defaultShaderStages,
  28988. defined: defined,
  28989. degrees: degrees,
  28990. deltaTime: deltaTime,
  28991. densityFog: densityFog,
  28992. densityFogFactor: densityFogFactor,
  28993. depth: depth,
  28994. depthPass: depthPass,
  28995. difference: difference,
  28996. diffuseColor: diffuseColor,
  28997. directPointLight: directPointLight,
  28998. directionToColor: directionToColor,
  28999. dispersion: dispersion,
  29000. distance: distance,
  29001. div: div,
  29002. dodge: dodge,
  29003. dot: dot,
  29004. drawIndex: drawIndex,
  29005. dynamicBufferAttribute: dynamicBufferAttribute,
  29006. element: element,
  29007. emissive: emissive,
  29008. equal: equal,
  29009. equals: equals,
  29010. equirectUV: equirectUV,
  29011. exp: exp,
  29012. exp2: exp2,
  29013. expression: expression,
  29014. faceDirection: faceDirection,
  29015. faceForward: faceForward,
  29016. faceforward: faceforward,
  29017. float: float,
  29018. floor: floor,
  29019. fog: fog,
  29020. fract: fract,
  29021. frameGroup: frameGroup,
  29022. frameId: frameId,
  29023. frontFacing: frontFacing,
  29024. fwidth: fwidth,
  29025. gain: gain,
  29026. gapSize: gapSize,
  29027. getConstNodeType: getConstNodeType,
  29028. getCurrentStack: getCurrentStack,
  29029. getDirection: getDirection,
  29030. getDistanceAttenuation: getDistanceAttenuation,
  29031. getGeometryRoughness: getGeometryRoughness,
  29032. getNormalFromDepth: getNormalFromDepth,
  29033. getParallaxCorrectNormal: getParallaxCorrectNormal,
  29034. getRoughness: getRoughness,
  29035. getScreenPosition: getScreenPosition,
  29036. getShIrradianceAt: getShIrradianceAt,
  29037. getTextureIndex: getTextureIndex,
  29038. getViewPosition: getViewPosition,
  29039. globalId: globalId,
  29040. glsl: glsl,
  29041. glslFn: glslFn,
  29042. grayscale: grayscale,
  29043. greaterThan: greaterThan,
  29044. greaterThanEqual: greaterThanEqual,
  29045. hash: hash,
  29046. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  29047. highpModelViewMatrix: highpModelViewMatrix,
  29048. hue: hue,
  29049. instance: instance,
  29050. instanceIndex: instanceIndex,
  29051. instancedArray: instancedArray,
  29052. instancedBufferAttribute: instancedBufferAttribute,
  29053. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  29054. instancedMesh: instancedMesh,
  29055. int: int,
  29056. inverseSqrt: inverseSqrt,
  29057. inversesqrt: inversesqrt,
  29058. invocationLocalIndex: invocationLocalIndex,
  29059. invocationSubgroupIndex: invocationSubgroupIndex,
  29060. ior: ior,
  29061. iridescence: iridescence,
  29062. iridescenceIOR: iridescenceIOR,
  29063. iridescenceThickness: iridescenceThickness,
  29064. ivec2: ivec2,
  29065. ivec3: ivec3,
  29066. ivec4: ivec4,
  29067. js: js,
  29068. label: label,
  29069. length: length,
  29070. lengthSq: lengthSq,
  29071. lessThan: lessThan,
  29072. lessThanEqual: lessThanEqual,
  29073. lightPosition: lightPosition,
  29074. lightProjectionUV: lightProjectionUV,
  29075. lightShadowMatrix: lightShadowMatrix,
  29076. lightTargetDirection: lightTargetDirection,
  29077. lightTargetPosition: lightTargetPosition,
  29078. lightViewPosition: lightViewPosition,
  29079. lightingContext: lightingContext,
  29080. lights: lights,
  29081. linearDepth: linearDepth,
  29082. linearToneMapping: linearToneMapping,
  29083. localId: localId,
  29084. log: log,
  29085. log2: log2,
  29086. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  29087. loop: loop,
  29088. luminance: luminance,
  29089. mat2: mat2,
  29090. mat3: mat3,
  29091. mat4: mat4,
  29092. matcapUV: matcapUV,
  29093. materialAO: materialAO,
  29094. materialAlphaTest: materialAlphaTest,
  29095. materialAnisotropy: materialAnisotropy,
  29096. materialAnisotropyVector: materialAnisotropyVector,
  29097. materialAttenuationColor: materialAttenuationColor,
  29098. materialAttenuationDistance: materialAttenuationDistance,
  29099. materialClearcoat: materialClearcoat,
  29100. materialClearcoatNormal: materialClearcoatNormal,
  29101. materialClearcoatRoughness: materialClearcoatRoughness,
  29102. materialColor: materialColor,
  29103. materialDispersion: materialDispersion,
  29104. materialEmissive: materialEmissive,
  29105. materialEnvIntensity: materialEnvIntensity,
  29106. materialEnvRotation: materialEnvRotation,
  29107. materialIOR: materialIOR,
  29108. materialIridescence: materialIridescence,
  29109. materialIridescenceIOR: materialIridescenceIOR,
  29110. materialIridescenceThickness: materialIridescenceThickness,
  29111. materialLightMap: materialLightMap,
  29112. materialLineDashOffset: materialLineDashOffset,
  29113. materialLineDashSize: materialLineDashSize,
  29114. materialLineGapSize: materialLineGapSize,
  29115. materialLineScale: materialLineScale,
  29116. materialLineWidth: materialLineWidth,
  29117. materialMetalness: materialMetalness,
  29118. materialNormal: materialNormal,
  29119. materialOpacity: materialOpacity,
  29120. materialPointSize: materialPointSize,
  29121. materialReference: materialReference,
  29122. materialReflectivity: materialReflectivity,
  29123. materialRefractionRatio: materialRefractionRatio,
  29124. materialRotation: materialRotation,
  29125. materialRoughness: materialRoughness,
  29126. materialSheen: materialSheen,
  29127. materialSheenRoughness: materialSheenRoughness,
  29128. materialShininess: materialShininess,
  29129. materialSpecular: materialSpecular,
  29130. materialSpecularColor: materialSpecularColor,
  29131. materialSpecularIntensity: materialSpecularIntensity,
  29132. materialSpecularStrength: materialSpecularStrength,
  29133. materialThickness: materialThickness,
  29134. materialTransmission: materialTransmission,
  29135. max: max$1,
  29136. maxMipLevel: maxMipLevel,
  29137. mediumpModelViewMatrix: mediumpModelViewMatrix,
  29138. metalness: metalness,
  29139. min: min$1,
  29140. mix: mix,
  29141. mixElement: mixElement,
  29142. mod: mod,
  29143. modInt: modInt,
  29144. modelDirection: modelDirection,
  29145. modelNormalMatrix: modelNormalMatrix,
  29146. modelPosition: modelPosition,
  29147. modelRadius: modelRadius,
  29148. modelScale: modelScale,
  29149. modelViewMatrix: modelViewMatrix,
  29150. modelViewPosition: modelViewPosition,
  29151. modelViewProjection: modelViewProjection,
  29152. modelWorldMatrix: modelWorldMatrix,
  29153. modelWorldMatrixInverse: modelWorldMatrixInverse,
  29154. morphReference: morphReference,
  29155. mrt: mrt,
  29156. mul: mul,
  29157. mx_aastep: mx_aastep,
  29158. mx_cell_noise_float: mx_cell_noise_float,
  29159. mx_contrast: mx_contrast,
  29160. mx_fractal_noise_float: mx_fractal_noise_float,
  29161. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  29162. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  29163. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  29164. mx_hsvtorgb: mx_hsvtorgb,
  29165. mx_noise_float: mx_noise_float,
  29166. mx_noise_vec3: mx_noise_vec3,
  29167. mx_noise_vec4: mx_noise_vec4,
  29168. mx_ramplr: mx_ramplr,
  29169. mx_ramptb: mx_ramptb,
  29170. mx_rgbtohsv: mx_rgbtohsv,
  29171. mx_safepower: mx_safepower,
  29172. mx_splitlr: mx_splitlr,
  29173. mx_splittb: mx_splittb,
  29174. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  29175. mx_transform_uv: mx_transform_uv,
  29176. mx_worley_noise_float: mx_worley_noise_float,
  29177. mx_worley_noise_vec2: mx_worley_noise_vec2,
  29178. mx_worley_noise_vec3: mx_worley_noise_vec3,
  29179. negate: negate,
  29180. neutralToneMapping: neutralToneMapping,
  29181. nodeArray: nodeArray,
  29182. nodeImmutable: nodeImmutable,
  29183. nodeObject: nodeObject,
  29184. nodeObjects: nodeObjects,
  29185. nodeProxy: nodeProxy,
  29186. normalFlat: normalFlat,
  29187. normalGeometry: normalGeometry,
  29188. normalLocal: normalLocal,
  29189. normalMap: normalMap,
  29190. normalView: normalView,
  29191. normalWorld: normalWorld,
  29192. normalize: normalize,
  29193. not: not,
  29194. notEqual: notEqual,
  29195. numWorkgroups: numWorkgroups,
  29196. objectDirection: objectDirection,
  29197. objectGroup: objectGroup,
  29198. objectPosition: objectPosition,
  29199. objectRadius: objectRadius,
  29200. objectScale: objectScale,
  29201. objectViewPosition: objectViewPosition,
  29202. objectWorldMatrix: objectWorldMatrix,
  29203. oneMinus: oneMinus,
  29204. or: or,
  29205. orthographicDepthToViewZ: orthographicDepthToViewZ,
  29206. oscSawtooth: oscSawtooth,
  29207. oscSine: oscSine,
  29208. oscSquare: oscSquare,
  29209. oscTriangle: oscTriangle,
  29210. output: output,
  29211. outputStruct: outputStruct,
  29212. overlay: overlay,
  29213. overloadingFn: overloadingFn,
  29214. parabola: parabola,
  29215. parallaxDirection: parallaxDirection,
  29216. parallaxUV: parallaxUV,
  29217. parameter: parameter,
  29218. pass: pass,
  29219. passTexture: passTexture,
  29220. pcurve: pcurve,
  29221. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  29222. pmremTexture: pmremTexture,
  29223. pointShadow: pointShadow,
  29224. pointUV: pointUV,
  29225. pointWidth: pointWidth,
  29226. positionGeometry: positionGeometry,
  29227. positionLocal: positionLocal,
  29228. positionPrevious: positionPrevious,
  29229. positionView: positionView,
  29230. positionViewDirection: positionViewDirection,
  29231. positionWorld: positionWorld,
  29232. positionWorldDirection: positionWorldDirection,
  29233. posterize: posterize,
  29234. pow: pow,
  29235. pow2: pow2,
  29236. pow3: pow3,
  29237. pow4: pow4,
  29238. property: property,
  29239. radians: radians,
  29240. rand: rand,
  29241. range: range,
  29242. rangeFog: rangeFog,
  29243. rangeFogFactor: rangeFogFactor,
  29244. reciprocal: reciprocal,
  29245. reference: reference,
  29246. referenceBuffer: referenceBuffer,
  29247. reflect: reflect,
  29248. reflectVector: reflectVector,
  29249. reflectView: reflectView,
  29250. reflector: reflector,
  29251. refract: refract,
  29252. refractVector: refractVector,
  29253. refractView: refractView,
  29254. reinhardToneMapping: reinhardToneMapping,
  29255. remainder: remainder,
  29256. remap: remap,
  29257. remapClamp: remapClamp,
  29258. renderGroup: renderGroup,
  29259. renderOutput: renderOutput,
  29260. rendererReference: rendererReference,
  29261. rotate: rotate,
  29262. rotateUV: rotateUV,
  29263. roughness: roughness,
  29264. round: round,
  29265. rtt: rtt,
  29266. sRGBTransferEOTF: sRGBTransferEOTF,
  29267. sRGBTransferOETF: sRGBTransferOETF,
  29268. sampler: sampler,
  29269. samplerComparison: samplerComparison,
  29270. saturate: saturate,
  29271. saturation: saturation,
  29272. screen: screen,
  29273. screenCoordinate: screenCoordinate,
  29274. screenSize: screenSize,
  29275. screenUV: screenUV,
  29276. scriptable: scriptable,
  29277. scriptableValue: scriptableValue,
  29278. select: select,
  29279. setCurrentStack: setCurrentStack,
  29280. shaderStages: shaderStages,
  29281. shadow: shadow,
  29282. shadowPositionWorld: shadowPositionWorld,
  29283. shapeCircle: shapeCircle,
  29284. sharedUniformGroup: sharedUniformGroup,
  29285. sheen: sheen,
  29286. sheenRoughness: sheenRoughness,
  29287. shiftLeft: shiftLeft,
  29288. shiftRight: shiftRight,
  29289. shininess: shininess,
  29290. sign: sign,
  29291. sin: sin,
  29292. sinc: sinc,
  29293. skinning: skinning,
  29294. skinningReference: skinningReference,
  29295. smoothstep: smoothstep,
  29296. smoothstepElement: smoothstepElement,
  29297. specularColor: specularColor,
  29298. specularF90: specularF90,
  29299. spherizeUV: spherizeUV,
  29300. split: split,
  29301. spritesheetUV: spritesheetUV,
  29302. sqrt: sqrt,
  29303. stack: stack,
  29304. step: step,
  29305. storage: storage,
  29306. storageBarrier: storageBarrier,
  29307. storageObject: storageObject,
  29308. storageTexture: storageTexture,
  29309. string: string,
  29310. struct: struct,
  29311. sub: sub,
  29312. subgroupIndex: subgroupIndex,
  29313. subgroupSize: subgroupSize,
  29314. tan: tan,
  29315. tangentGeometry: tangentGeometry,
  29316. tangentLocal: tangentLocal,
  29317. tangentView: tangentView,
  29318. tangentWorld: tangentWorld,
  29319. temp: temp,
  29320. texture: texture,
  29321. texture3D: texture3D,
  29322. textureBarrier: textureBarrier,
  29323. textureBicubic: textureBicubic,
  29324. textureCubeUV: textureCubeUV,
  29325. textureLoad: textureLoad,
  29326. textureSize: textureSize,
  29327. textureStore: textureStore,
  29328. thickness: thickness,
  29329. time: time,
  29330. timerDelta: timerDelta,
  29331. timerGlobal: timerGlobal,
  29332. timerLocal: timerLocal,
  29333. toOutputColorSpace: toOutputColorSpace,
  29334. toWorkingColorSpace: toWorkingColorSpace,
  29335. toneMapping: toneMapping,
  29336. toneMappingExposure: toneMappingExposure,
  29337. toonOutlinePass: toonOutlinePass,
  29338. transformDirection: transformDirection,
  29339. transformNormal: transformNormal,
  29340. transformNormalToView: transformNormalToView,
  29341. transformedBentNormalView: transformedBentNormalView,
  29342. transformedBitangentView: transformedBitangentView,
  29343. transformedBitangentWorld: transformedBitangentWorld,
  29344. transformedClearcoatNormalView: transformedClearcoatNormalView,
  29345. transformedNormalView: transformedNormalView,
  29346. transformedNormalWorld: transformedNormalWorld,
  29347. transformedTangentView: transformedTangentView,
  29348. transformedTangentWorld: transformedTangentWorld,
  29349. transmission: transmission,
  29350. transpose: transpose,
  29351. triNoise3D: triNoise3D,
  29352. triplanarTexture: triplanarTexture,
  29353. triplanarTextures: triplanarTextures,
  29354. trunc: trunc,
  29355. tslFn: tslFn,
  29356. uint: uint,
  29357. uniform: uniform,
  29358. uniformArray: uniformArray,
  29359. uniformGroup: uniformGroup,
  29360. uniforms: uniforms,
  29361. userData: userData,
  29362. uv: uv,
  29363. uvec2: uvec2,
  29364. uvec3: uvec3,
  29365. uvec4: uvec4,
  29366. varying: varying,
  29367. varyingProperty: varyingProperty,
  29368. vec2: vec2,
  29369. vec3: vec3,
  29370. vec4: vec4,
  29371. vectorComponents: vectorComponents,
  29372. velocity: velocity,
  29373. vertexColor: vertexColor,
  29374. vertexIndex: vertexIndex,
  29375. vertexStage: vertexStage,
  29376. vibrance: vibrance,
  29377. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  29378. viewZToOrthographicDepth: viewZToOrthographicDepth,
  29379. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  29380. viewport: viewport,
  29381. viewportBottomLeft: viewportBottomLeft,
  29382. viewportCoordinate: viewportCoordinate,
  29383. viewportDepthTexture: viewportDepthTexture,
  29384. viewportLinearDepth: viewportLinearDepth,
  29385. viewportMipTexture: viewportMipTexture,
  29386. viewportResolution: viewportResolution,
  29387. viewportSafeUV: viewportSafeUV,
  29388. viewportSharedTexture: viewportSharedTexture,
  29389. viewportSize: viewportSize,
  29390. viewportTexture: viewportTexture,
  29391. viewportTopLeft: viewportTopLeft,
  29392. viewportUV: viewportUV,
  29393. wgsl: wgsl,
  29394. wgslFn: wgslFn,
  29395. workgroupArray: workgroupArray,
  29396. workgroupBarrier: workgroupBarrier,
  29397. workgroupId: workgroupId,
  29398. workingToColorSpace: workingToColorSpace,
  29399. xor: xor
  29400. });
  29401. const _clearColor = /*@__PURE__*/ new Color4();
  29402. /**
  29403. * This renderer module manages the background.
  29404. *
  29405. * @private
  29406. * @augments DataMap
  29407. */
  29408. class Background extends DataMap {
  29409. /**
  29410. * Constructs a new background management component.
  29411. *
  29412. * @param {Renderer} renderer - The renderer.
  29413. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  29414. */
  29415. constructor( renderer, nodes ) {
  29416. super();
  29417. /**
  29418. * The renderer.
  29419. *
  29420. * @type {Renderer}
  29421. */
  29422. this.renderer = renderer;
  29423. /**
  29424. * Renderer component for managing nodes related logic.
  29425. *
  29426. * @type {Nodes}
  29427. */
  29428. this.nodes = nodes;
  29429. }
  29430. /**
  29431. * Updates the background for the given scene. Depending on how `Scene.background`
  29432. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  29433. * or add a mesh to the render list for rendering the background as a textured plane
  29434. * or skybox.
  29435. *
  29436. * @param {Scene} scene - The scene.
  29437. * @param {RenderList} renderList - The current render list.
  29438. * @param {RenderContext} renderContext - The current render context.
  29439. */
  29440. update( scene, renderList, renderContext ) {
  29441. const renderer = this.renderer;
  29442. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  29443. let forceClear = false;
  29444. if ( background === null ) {
  29445. // no background settings, use clear color configuration from the renderer
  29446. renderer._clearColor.getRGB( _clearColor );
  29447. _clearColor.a = renderer._clearColor.a;
  29448. } else if ( background.isColor === true ) {
  29449. // background is an opaque color
  29450. background.getRGB( _clearColor );
  29451. _clearColor.a = 1;
  29452. forceClear = true;
  29453. } else if ( background.isNode === true ) {
  29454. const sceneData = this.get( scene );
  29455. const backgroundNode = background;
  29456. _clearColor.copy( renderer._clearColor );
  29457. let backgroundMesh = sceneData.backgroundMesh;
  29458. if ( backgroundMesh === undefined ) {
  29459. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  29460. // @TODO: Add Texture2D support using node context
  29461. getUV: () => backgroundRotation.mul( normalWorld ),
  29462. getTextureLevel: () => backgroundBlurriness
  29463. } );
  29464. let viewProj = modelViewProjection;
  29465. viewProj = viewProj.setZ( viewProj.w );
  29466. const nodeMaterial = new NodeMaterial();
  29467. nodeMaterial.name = 'Background.material';
  29468. nodeMaterial.side = BackSide;
  29469. nodeMaterial.depthTest = false;
  29470. nodeMaterial.depthWrite = false;
  29471. nodeMaterial.fog = false;
  29472. nodeMaterial.lights = false;
  29473. nodeMaterial.vertexNode = viewProj;
  29474. nodeMaterial.colorNode = backgroundMeshNode;
  29475. sceneData.backgroundMeshNode = backgroundMeshNode;
  29476. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  29477. backgroundMesh.frustumCulled = false;
  29478. backgroundMesh.name = 'Background.mesh';
  29479. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  29480. this.matrixWorld.copyPosition( camera.matrixWorld );
  29481. };
  29482. }
  29483. const backgroundCacheKey = backgroundNode.getCacheKey();
  29484. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  29485. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  29486. sceneData.backgroundMeshNode.needsUpdate = true;
  29487. backgroundMesh.material.needsUpdate = true;
  29488. sceneData.backgroundCacheKey = backgroundCacheKey;
  29489. }
  29490. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  29491. } else {
  29492. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  29493. }
  29494. //
  29495. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  29496. if ( environmentBlendMode === 'additive' ) {
  29497. _clearColor.set( 0, 0, 0, 1 );
  29498. } else if ( environmentBlendMode === 'alpha-blend' ) {
  29499. _clearColor.set( 0, 0, 0, 0 );
  29500. }
  29501. //
  29502. if ( renderer.autoClear === true || forceClear === true ) {
  29503. const clearColorValue = renderContext.clearColorValue;
  29504. clearColorValue.r = _clearColor.r;
  29505. clearColorValue.g = _clearColor.g;
  29506. clearColorValue.b = _clearColor.b;
  29507. clearColorValue.a = _clearColor.a;
  29508. // premultiply alpha
  29509. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  29510. clearColorValue.r *= clearColorValue.a;
  29511. clearColorValue.g *= clearColorValue.a;
  29512. clearColorValue.b *= clearColorValue.a;
  29513. }
  29514. //
  29515. renderContext.depthClearValue = renderer._clearDepth;
  29516. renderContext.stencilClearValue = renderer._clearStencil;
  29517. renderContext.clearColor = renderer.autoClearColor === true;
  29518. renderContext.clearDepth = renderer.autoClearDepth === true;
  29519. renderContext.clearStencil = renderer.autoClearStencil === true;
  29520. } else {
  29521. renderContext.clearColor = false;
  29522. renderContext.clearDepth = false;
  29523. renderContext.clearStencil = false;
  29524. }
  29525. }
  29526. }
  29527. let _id$6 = 0;
  29528. /**
  29529. * A bind group represents a collection of bindings and thus a collection
  29530. * or resources. Bind groups are assigned to pipelines to provide them
  29531. * with the required resources (like uniform buffers or textures).
  29532. *
  29533. * @private
  29534. */
  29535. class BindGroup {
  29536. /**
  29537. * Constructs a new bind group.
  29538. *
  29539. * @param {string} name - The bind group's name.
  29540. * @param {Array<Binding>} bindings - An array of bindings.
  29541. * @param {number} index - The group index.
  29542. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  29543. */
  29544. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  29545. /**
  29546. * The bind group's name.
  29547. *
  29548. * @type {string}
  29549. */
  29550. this.name = name;
  29551. /**
  29552. * An array of bindings.
  29553. *
  29554. * @type {Array<Binding>}
  29555. */
  29556. this.bindings = bindings;
  29557. /**
  29558. * The group index.
  29559. *
  29560. * @type {number}
  29561. */
  29562. this.index = index;
  29563. /**
  29564. * An array of reference bindings.
  29565. *
  29566. * @type {Array<Binding>}
  29567. */
  29568. this.bindingsReference = bindingsReference;
  29569. /**
  29570. * The group's ID.
  29571. *
  29572. * @type {number}
  29573. */
  29574. this.id = _id$6 ++;
  29575. }
  29576. }
  29577. /**
  29578. * This module represents the state of a node builder after it was
  29579. * used to build the nodes for a render object. The state holds the
  29580. * results of the build for further processing in the renderer.
  29581. *
  29582. * Render objects with identical cache keys share the same node builder state.
  29583. *
  29584. * @private
  29585. */
  29586. class NodeBuilderState {
  29587. /**
  29588. * Constructs a new node builder state.
  29589. *
  29590. * @param {string} vertexShader - The native vertex shader code.
  29591. * @param {string} fragmentShader - The native fragment shader code.
  29592. * @param {string} computeShader - The native compute shader code.
  29593. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  29594. * @param {Array<BindGroup>} bindings - An array of bind groups.
  29595. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  29596. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  29597. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  29598. * @param {NodeMaterialObserver} observer - A node material observer.
  29599. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  29600. */
  29601. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  29602. /**
  29603. * The native vertex shader code.
  29604. *
  29605. * @type {string}
  29606. */
  29607. this.vertexShader = vertexShader;
  29608. /**
  29609. * The native fragment shader code.
  29610. *
  29611. * @type {string}
  29612. */
  29613. this.fragmentShader = fragmentShader;
  29614. /**
  29615. * The native compute shader code.
  29616. *
  29617. * @type {string}
  29618. */
  29619. this.computeShader = computeShader;
  29620. /**
  29621. * An array with transform attribute objects.
  29622. * Only relevant when using compute shaders with WebGL 2.
  29623. *
  29624. * @type {Array<Object>}
  29625. */
  29626. this.transforms = transforms;
  29627. /**
  29628. * An array of node attributes representing
  29629. * the attributes of the shaders.
  29630. *
  29631. * @type {Array<NodeAttribute>}
  29632. */
  29633. this.nodeAttributes = nodeAttributes;
  29634. /**
  29635. * An array of bind groups representing the uniform or storage
  29636. * buffers, texture or samplers of the shader.
  29637. *
  29638. * @type {Array<BindGroup>}
  29639. */
  29640. this.bindings = bindings;
  29641. /**
  29642. * An array of nodes that implement their `update()` method.
  29643. *
  29644. * @type {Array<Node>}
  29645. */
  29646. this.updateNodes = updateNodes;
  29647. /**
  29648. * An array of nodes that implement their `updateBefore()` method.
  29649. *
  29650. * @type {Array<Node>}
  29651. */
  29652. this.updateBeforeNodes = updateBeforeNodes;
  29653. /**
  29654. * An array of nodes that implement their `updateAfter()` method.
  29655. *
  29656. * @type {Array<Node>}
  29657. */
  29658. this.updateAfterNodes = updateAfterNodes;
  29659. /**
  29660. * A node material observer.
  29661. *
  29662. * @type {NodeMaterialObserver}
  29663. */
  29664. this.observer = observer;
  29665. /**
  29666. * How often this state is used by render objects.
  29667. *
  29668. * @type {number}
  29669. */
  29670. this.usedTimes = 0;
  29671. }
  29672. /**
  29673. * This method is used to create a array of bind groups based
  29674. * on the existing bind groups of this state. Shared groups are
  29675. * not cloned.
  29676. *
  29677. * @return {Array<BindGroup>} A array of bind groups.
  29678. */
  29679. createBindings() {
  29680. const bindings = [];
  29681. for ( const instanceGroup of this.bindings ) {
  29682. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  29683. if ( shared !== true ) {
  29684. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  29685. bindings.push( bindingsGroup );
  29686. for ( const instanceBinding of instanceGroup.bindings ) {
  29687. bindingsGroup.bindings.push( instanceBinding.clone() );
  29688. }
  29689. } else {
  29690. bindings.push( instanceGroup );
  29691. }
  29692. }
  29693. return bindings;
  29694. }
  29695. }
  29696. /**
  29697. * {@link NodeBuilder} is going to create instances of this class during the build process
  29698. * of nodes. They represent the final shader attributes that are going to be generated
  29699. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  29700. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  29701. */
  29702. class NodeAttribute {
  29703. /**
  29704. * Constructs a new node attribute.
  29705. *
  29706. * @param {string} name - The name of the attribute.
  29707. * @param {string} type - The type of the attribute.
  29708. * @param {?Node} node - An optional reference to the node.
  29709. */
  29710. constructor( name, type, node = null ) {
  29711. /**
  29712. * This flag can be used for type testing.
  29713. *
  29714. * @type {boolean}
  29715. * @readonly
  29716. * @default true
  29717. */
  29718. this.isNodeAttribute = true;
  29719. /**
  29720. * The name of the attribute.
  29721. *
  29722. * @type {string}
  29723. */
  29724. this.name = name;
  29725. /**
  29726. * The type of the attribute.
  29727. *
  29728. * @type {string}
  29729. */
  29730. this.type = type;
  29731. /**
  29732. * An optional reference to the node.
  29733. *
  29734. * @type {?Node}
  29735. * @default null
  29736. */
  29737. this.node = node;
  29738. }
  29739. }
  29740. /**
  29741. * {@link NodeBuilder} is going to create instances of this class during the build process
  29742. * of nodes. They represent the final shader uniforms that are going to be generated
  29743. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  29744. * for this purpose.
  29745. */
  29746. class NodeUniform {
  29747. /**
  29748. * Constructs a new node uniform.
  29749. *
  29750. * @param {string} name - The name of the uniform.
  29751. * @param {string} type - The type of the uniform.
  29752. * @param {UniformNode} node - An reference to the node.
  29753. */
  29754. constructor( name, type, node ) {
  29755. /**
  29756. * This flag can be used for type testing.
  29757. *
  29758. * @type {boolean}
  29759. * @readonly
  29760. * @default true
  29761. */
  29762. this.isNodeUniform = true;
  29763. /**
  29764. * The name of the uniform.
  29765. *
  29766. * @type {string}
  29767. */
  29768. this.name = name;
  29769. /**
  29770. * The type of the uniform.
  29771. *
  29772. * @type {string}
  29773. */
  29774. this.type = type;
  29775. /**
  29776. * An reference to the node.
  29777. *
  29778. * @type {UniformNode}
  29779. */
  29780. this.node = node.getSelf();
  29781. }
  29782. /**
  29783. * The value of the uniform node.
  29784. *
  29785. * @type {any}
  29786. */
  29787. get value() {
  29788. return this.node.value;
  29789. }
  29790. set value( val ) {
  29791. this.node.value = val;
  29792. }
  29793. /**
  29794. * The id of the uniform node.
  29795. *
  29796. * @type {number}
  29797. */
  29798. get id() {
  29799. return this.node.id;
  29800. }
  29801. /**
  29802. * The uniform node's group.
  29803. *
  29804. * @type {UniformGroupNode}
  29805. */
  29806. get groupNode() {
  29807. return this.node.groupNode;
  29808. }
  29809. }
  29810. /**
  29811. * {@link NodeBuilder} is going to create instances of this class during the build process
  29812. * of nodes. They represent the final shader variables that are going to be generated
  29813. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  29814. * this purpose.
  29815. */
  29816. class NodeVar {
  29817. /**
  29818. * Constructs a new node variable.
  29819. *
  29820. * @param {string} name - The name of the variable.
  29821. * @param {string} type - The type of the variable.
  29822. * @param {boolean} [readOnly=false] - The read-only flag.
  29823. * @param {?number} [count=null] - The size.
  29824. */
  29825. constructor( name, type, readOnly = false, count = null ) {
  29826. /**
  29827. * This flag can be used for type testing.
  29828. *
  29829. * @type {boolean}
  29830. * @readonly
  29831. * @default true
  29832. */
  29833. this.isNodeVar = true;
  29834. /**
  29835. * The name of the variable.
  29836. *
  29837. * @type {string}
  29838. */
  29839. this.name = name;
  29840. /**
  29841. * The type of the variable.
  29842. *
  29843. * @type {string}
  29844. */
  29845. this.type = type;
  29846. /**
  29847. * The read-only flag.
  29848. *
  29849. * @type {boolean}
  29850. */
  29851. this.readOnly = readOnly;
  29852. /**
  29853. * The size.
  29854. *
  29855. * @type {?number}
  29856. */
  29857. this.count = count;
  29858. }
  29859. }
  29860. /**
  29861. * {@link NodeBuilder} is going to create instances of this class during the build process
  29862. * of nodes. They represent the final shader varyings that are going to be generated
  29863. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  29864. * this purpose.
  29865. *
  29866. * @augments NodeVar
  29867. */
  29868. class NodeVarying extends NodeVar {
  29869. /**
  29870. * Constructs a new node varying.
  29871. *
  29872. * @param {string} name - The name of the varying.
  29873. * @param {string} type - The type of the varying.
  29874. */
  29875. constructor( name, type ) {
  29876. super( name, type );
  29877. /**
  29878. * Whether this varying requires interpolation or not. This property can be used
  29879. * to check if the varying can be optimized for a variable.
  29880. *
  29881. * @type {boolean}
  29882. * @default false
  29883. */
  29884. this.needsInterpolation = false;
  29885. /**
  29886. * This flag can be used for type testing.
  29887. *
  29888. * @type {boolean}
  29889. * @readonly
  29890. * @default true
  29891. */
  29892. this.isNodeVarying = true;
  29893. }
  29894. }
  29895. /**
  29896. * {@link NodeBuilder} is going to create instances of this class during the build process
  29897. * of nodes. They represent user-defined, native shader code portions that are going to be
  29898. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  29899. * for this purpose.
  29900. */
  29901. class NodeCode {
  29902. /**
  29903. * Constructs a new code node.
  29904. *
  29905. * @param {string} name - The name of the code.
  29906. * @param {string} type - The node type.
  29907. * @param {string} [code=''] - The native shader code.
  29908. */
  29909. constructor( name, type, code = '' ) {
  29910. /**
  29911. * The name of the code.
  29912. *
  29913. * @type {string}
  29914. */
  29915. this.name = name;
  29916. /**
  29917. * The node type.
  29918. *
  29919. * @type {string}
  29920. */
  29921. this.type = type;
  29922. /**
  29923. * The native shader code.
  29924. *
  29925. * @type {string}
  29926. * @default ''
  29927. */
  29928. this.code = code;
  29929. Object.defineProperty( this, 'isNodeCode', { value: true } );
  29930. }
  29931. }
  29932. let _id$5 = 0;
  29933. /**
  29934. * This utility class is used in {@link NodeBuilder} as an internal
  29935. * cache data structure for node data.
  29936. */
  29937. class NodeCache {
  29938. /**
  29939. * Constructs a new node cache.
  29940. *
  29941. * @param {?NodeCache} parent - A reference to a parent cache.
  29942. */
  29943. constructor( parent = null ) {
  29944. /**
  29945. * The id of the cache.
  29946. *
  29947. * @type {number}
  29948. * @readonly
  29949. */
  29950. this.id = _id$5 ++;
  29951. /**
  29952. * A weak map for managing node data.
  29953. *
  29954. * @type {WeakMap<Node, Object>}
  29955. */
  29956. this.nodesData = new WeakMap();
  29957. /**
  29958. * Reference to a parent node cache.
  29959. *
  29960. * @type {?NodeCache}
  29961. * @default null
  29962. */
  29963. this.parent = parent;
  29964. }
  29965. /**
  29966. * Returns the data for the given node.
  29967. *
  29968. * @param {Node} node - The node.
  29969. * @return {?Object} The data for the node.
  29970. */
  29971. getData( node ) {
  29972. let data = this.nodesData.get( node );
  29973. if ( data === undefined && this.parent !== null ) {
  29974. data = this.parent.getData( node );
  29975. }
  29976. return data;
  29977. }
  29978. /**
  29979. * Sets the data for a given node.
  29980. *
  29981. * @param {Node} node - The node.
  29982. * @param {Object} data - The data that should be cached.
  29983. */
  29984. setData( node, data ) {
  29985. this.nodesData.set( node, data );
  29986. }
  29987. }
  29988. class StructType {
  29989. constructor( name, members ) {
  29990. this.name = name;
  29991. this.members = members;
  29992. this.output = false;
  29993. }
  29994. }
  29995. /**
  29996. * Abstract base class for uniforms.
  29997. *
  29998. * @abstract
  29999. * @private
  30000. */
  30001. class Uniform {
  30002. /**
  30003. * Constructs a new uniform.
  30004. *
  30005. * @param {string} name - The uniform's name.
  30006. * @param {any} value - The uniform's value.
  30007. */
  30008. constructor( name, value ) {
  30009. /**
  30010. * The uniform's name.
  30011. *
  30012. * @type {string}
  30013. */
  30014. this.name = name;
  30015. /**
  30016. * The uniform's value.
  30017. *
  30018. * @type {any}
  30019. */
  30020. this.value = value;
  30021. /**
  30022. * Used to build the uniform buffer according to the STD140 layout.
  30023. * Derived uniforms will set this property to a data type specific
  30024. * value.
  30025. *
  30026. * @type {number}
  30027. */
  30028. this.boundary = 0;
  30029. /**
  30030. * The item size. Derived uniforms will set this property to a data
  30031. * type specific value.
  30032. *
  30033. * @type {number}
  30034. */
  30035. this.itemSize = 0;
  30036. /**
  30037. * This property is set by {@link UniformsGroup} and marks
  30038. * the start position in the uniform buffer.
  30039. *
  30040. * @type {number}
  30041. */
  30042. this.offset = 0;
  30043. }
  30044. /**
  30045. * Sets the uniform's value.
  30046. *
  30047. * @param {any} value - The value to set.
  30048. */
  30049. setValue( value ) {
  30050. this.value = value;
  30051. }
  30052. /**
  30053. * Returns the uniform's value.
  30054. *
  30055. * @return {any} The value.
  30056. */
  30057. getValue() {
  30058. return this.value;
  30059. }
  30060. }
  30061. /**
  30062. * Represents a Number uniform.
  30063. *
  30064. * @private
  30065. * @augments Uniform
  30066. */
  30067. class NumberUniform extends Uniform {
  30068. /**
  30069. * Constructs a new Number uniform.
  30070. *
  30071. * @param {string} name - The uniform's name.
  30072. * @param {number} value - The uniform's value.
  30073. */
  30074. constructor( name, value = 0 ) {
  30075. super( name, value );
  30076. /**
  30077. * This flag can be used for type testing.
  30078. *
  30079. * @type {boolean}
  30080. * @readonly
  30081. * @default true
  30082. */
  30083. this.isNumberUniform = true;
  30084. this.boundary = 4;
  30085. this.itemSize = 1;
  30086. }
  30087. }
  30088. /**
  30089. * Represents a Vector2 uniform.
  30090. *
  30091. * @private
  30092. * @augments Uniform
  30093. */
  30094. class Vector2Uniform extends Uniform {
  30095. /**
  30096. * Constructs a new Number uniform.
  30097. *
  30098. * @param {string} name - The uniform's name.
  30099. * @param {Vector2} value - The uniform's value.
  30100. */
  30101. constructor( name, value = new Vector2() ) {
  30102. super( name, value );
  30103. /**
  30104. * This flag can be used for type testing.
  30105. *
  30106. * @type {boolean}
  30107. * @readonly
  30108. * @default true
  30109. */
  30110. this.isVector2Uniform = true;
  30111. this.boundary = 8;
  30112. this.itemSize = 2;
  30113. }
  30114. }
  30115. /**
  30116. * Represents a Vector3 uniform.
  30117. *
  30118. * @private
  30119. * @augments Uniform
  30120. */
  30121. class Vector3Uniform extends Uniform {
  30122. /**
  30123. * Constructs a new Number uniform.
  30124. *
  30125. * @param {string} name - The uniform's name.
  30126. * @param {Vector3} value - The uniform's value.
  30127. */
  30128. constructor( name, value = new Vector3() ) {
  30129. super( name, value );
  30130. /**
  30131. * This flag can be used for type testing.
  30132. *
  30133. * @type {boolean}
  30134. * @readonly
  30135. * @default true
  30136. */
  30137. this.isVector3Uniform = true;
  30138. this.boundary = 16;
  30139. this.itemSize = 3;
  30140. }
  30141. }
  30142. /**
  30143. * Represents a Vector4 uniform.
  30144. *
  30145. * @private
  30146. * @augments Uniform
  30147. */
  30148. class Vector4Uniform extends Uniform {
  30149. /**
  30150. * Constructs a new Number uniform.
  30151. *
  30152. * @param {string} name - The uniform's name.
  30153. * @param {Vector4} value - The uniform's value.
  30154. */
  30155. constructor( name, value = new Vector4() ) {
  30156. super( name, value );
  30157. /**
  30158. * This flag can be used for type testing.
  30159. *
  30160. * @type {boolean}
  30161. * @readonly
  30162. * @default true
  30163. */
  30164. this.isVector4Uniform = true;
  30165. this.boundary = 16;
  30166. this.itemSize = 4;
  30167. }
  30168. }
  30169. /**
  30170. * Represents a Color uniform.
  30171. *
  30172. * @private
  30173. * @augments Uniform
  30174. */
  30175. class ColorUniform extends Uniform {
  30176. /**
  30177. * Constructs a new Number uniform.
  30178. *
  30179. * @param {string} name - The uniform's name.
  30180. * @param {Color} value - The uniform's value.
  30181. */
  30182. constructor( name, value = new Color() ) {
  30183. super( name, value );
  30184. /**
  30185. * This flag can be used for type testing.
  30186. *
  30187. * @type {boolean}
  30188. * @readonly
  30189. * @default true
  30190. */
  30191. this.isColorUniform = true;
  30192. this.boundary = 16;
  30193. this.itemSize = 3;
  30194. }
  30195. }
  30196. /**
  30197. * Represents a Matrix2 uniform.
  30198. *
  30199. * @private
  30200. * @augments Uniform
  30201. */
  30202. class Matrix2Uniform extends Uniform {
  30203. /**
  30204. * Constructs a new Number uniform.
  30205. *
  30206. * @param {string} name - The uniform's name.
  30207. * @param {Matrix2} value - The uniform's value.
  30208. */
  30209. constructor( name, value = new Matrix2() ) {
  30210. super( name, value );
  30211. /**
  30212. * This flag can be used for type testing.
  30213. *
  30214. * @type {boolean}
  30215. * @readonly
  30216. * @default true
  30217. */
  30218. this.isMatrix2Uniform = true;
  30219. this.boundary = 16;
  30220. this.itemSize = 4;
  30221. }
  30222. }
  30223. /**
  30224. * Represents a Matrix3 uniform.
  30225. *
  30226. * @private
  30227. * @augments Uniform
  30228. */
  30229. class Matrix3Uniform extends Uniform {
  30230. /**
  30231. * Constructs a new Number uniform.
  30232. *
  30233. * @param {string} name - The uniform's name.
  30234. * @param {Matrix3} value - The uniform's value.
  30235. */
  30236. constructor( name, value = new Matrix3() ) {
  30237. super( name, value );
  30238. /**
  30239. * This flag can be used for type testing.
  30240. *
  30241. * @type {boolean}
  30242. * @readonly
  30243. * @default true
  30244. */
  30245. this.isMatrix3Uniform = true;
  30246. this.boundary = 48;
  30247. this.itemSize = 12;
  30248. }
  30249. }
  30250. /**
  30251. * Represents a Matrix4 uniform.
  30252. *
  30253. * @private
  30254. * @augments Uniform
  30255. */
  30256. class Matrix4Uniform extends Uniform {
  30257. /**
  30258. * Constructs a new Number uniform.
  30259. *
  30260. * @param {string} name - The uniform's name.
  30261. * @param {Matrix4} value - The uniform's value.
  30262. */
  30263. constructor( name, value = new Matrix4() ) {
  30264. super( name, value );
  30265. /**
  30266. * This flag can be used for type testing.
  30267. *
  30268. * @type {boolean}
  30269. * @readonly
  30270. * @default true
  30271. */
  30272. this.isMatrix4Uniform = true;
  30273. this.boundary = 64;
  30274. this.itemSize = 16;
  30275. }
  30276. }
  30277. /**
  30278. * A special form of Number uniform binding type.
  30279. * It's value is managed by a node object.
  30280. *
  30281. * @private
  30282. * @augments NumberUniform
  30283. */
  30284. class NumberNodeUniform extends NumberUniform {
  30285. /**
  30286. * Constructs a new node-based Number uniform.
  30287. *
  30288. * @param {NodeUniform} nodeUniform - The node uniform.
  30289. */
  30290. constructor( nodeUniform ) {
  30291. super( nodeUniform.name, nodeUniform.value );
  30292. /**
  30293. * The node uniform.
  30294. *
  30295. * @type {NodeUniform}
  30296. */
  30297. this.nodeUniform = nodeUniform;
  30298. }
  30299. /**
  30300. * Overwritten to return the value of the node uniform.
  30301. *
  30302. * @return {number} The value.
  30303. */
  30304. getValue() {
  30305. return this.nodeUniform.value;
  30306. }
  30307. /**
  30308. * Returns the node uniform data type.
  30309. *
  30310. * @return {string} The data type.
  30311. */
  30312. getType() {
  30313. return this.nodeUniform.type;
  30314. }
  30315. }
  30316. /**
  30317. * A special form of Vector2 uniform binding type.
  30318. * It's value is managed by a node object.
  30319. *
  30320. * @private
  30321. * @augments Vector2Uniform
  30322. */
  30323. class Vector2NodeUniform extends Vector2Uniform {
  30324. /**
  30325. * Constructs a new node-based Vector2 uniform.
  30326. *
  30327. * @param {NodeUniform} nodeUniform - The node uniform.
  30328. */
  30329. constructor( nodeUniform ) {
  30330. super( nodeUniform.name, nodeUniform.value );
  30331. /**
  30332. * The node uniform.
  30333. *
  30334. * @type {NodeUniform}
  30335. */
  30336. this.nodeUniform = nodeUniform;
  30337. }
  30338. /**
  30339. * Overwritten to return the value of the node uniform.
  30340. *
  30341. * @return {Vector2} The value.
  30342. */
  30343. getValue() {
  30344. return this.nodeUniform.value;
  30345. }
  30346. /**
  30347. * Returns the node uniform data type.
  30348. *
  30349. * @return {string} The data type.
  30350. */
  30351. getType() {
  30352. return this.nodeUniform.type;
  30353. }
  30354. }
  30355. /**
  30356. * A special form of Vector3 uniform binding type.
  30357. * It's value is managed by a node object.
  30358. *
  30359. * @private
  30360. * @augments Vector3Uniform
  30361. */
  30362. class Vector3NodeUniform extends Vector3Uniform {
  30363. /**
  30364. * Constructs a new node-based Vector3 uniform.
  30365. *
  30366. * @param {NodeUniform} nodeUniform - The node uniform.
  30367. */
  30368. constructor( nodeUniform ) {
  30369. super( nodeUniform.name, nodeUniform.value );
  30370. /**
  30371. * The node uniform.
  30372. *
  30373. * @type {NodeUniform}
  30374. */
  30375. this.nodeUniform = nodeUniform;
  30376. }
  30377. /**
  30378. * Overwritten to return the value of the node uniform.
  30379. *
  30380. * @return {Vector3} The value.
  30381. */
  30382. getValue() {
  30383. return this.nodeUniform.value;
  30384. }
  30385. /**
  30386. * Returns the node uniform data type.
  30387. *
  30388. * @return {string} The data type.
  30389. */
  30390. getType() {
  30391. return this.nodeUniform.type;
  30392. }
  30393. }
  30394. /**
  30395. * A special form of Vector4 uniform binding type.
  30396. * It's value is managed by a node object.
  30397. *
  30398. * @private
  30399. * @augments Vector4Uniform
  30400. */
  30401. class Vector4NodeUniform extends Vector4Uniform {
  30402. /**
  30403. * Constructs a new node-based Vector4 uniform.
  30404. *
  30405. * @param {NodeUniform} nodeUniform - The node uniform.
  30406. */
  30407. constructor( nodeUniform ) {
  30408. super( nodeUniform.name, nodeUniform.value );
  30409. /**
  30410. * The node uniform.
  30411. *
  30412. * @type {NodeUniform}
  30413. */
  30414. this.nodeUniform = nodeUniform;
  30415. }
  30416. /**
  30417. * Overwritten to return the value of the node uniform.
  30418. *
  30419. * @return {Vector4} The value.
  30420. */
  30421. getValue() {
  30422. return this.nodeUniform.value;
  30423. }
  30424. /**
  30425. * Returns the node uniform data type.
  30426. *
  30427. * @return {string} The data type.
  30428. */
  30429. getType() {
  30430. return this.nodeUniform.type;
  30431. }
  30432. }
  30433. /**
  30434. * A special form of Color uniform binding type.
  30435. * It's value is managed by a node object.
  30436. *
  30437. * @private
  30438. * @augments ColorUniform
  30439. */
  30440. class ColorNodeUniform extends ColorUniform {
  30441. /**
  30442. * Constructs a new node-based Color uniform.
  30443. *
  30444. * @param {NodeUniform} nodeUniform - The node uniform.
  30445. */
  30446. constructor( nodeUniform ) {
  30447. super( nodeUniform.name, nodeUniform.value );
  30448. /**
  30449. * The node uniform.
  30450. *
  30451. * @type {NodeUniform}
  30452. */
  30453. this.nodeUniform = nodeUniform;
  30454. }
  30455. /**
  30456. * Overwritten to return the value of the node uniform.
  30457. *
  30458. * @return {Color} The value.
  30459. */
  30460. getValue() {
  30461. return this.nodeUniform.value;
  30462. }
  30463. /**
  30464. * Returns the node uniform data type.
  30465. *
  30466. * @return {string} The data type.
  30467. */
  30468. getType() {
  30469. return this.nodeUniform.type;
  30470. }
  30471. }
  30472. /**
  30473. * A special form of Matrix2 uniform binding type.
  30474. * It's value is managed by a node object.
  30475. *
  30476. * @private
  30477. * @augments Matrix2Uniform
  30478. */
  30479. class Matrix2NodeUniform extends Matrix2Uniform {
  30480. /**
  30481. * Constructs a new node-based Matrix2 uniform.
  30482. *
  30483. * @param {NodeUniform} nodeUniform - The node uniform.
  30484. */
  30485. constructor( nodeUniform ) {
  30486. super( nodeUniform.name, nodeUniform.value );
  30487. /**
  30488. * The node uniform.
  30489. *
  30490. * @type {NodeUniform}
  30491. */
  30492. this.nodeUniform = nodeUniform;
  30493. }
  30494. /**
  30495. * Overwritten to return the value of the node uniform.
  30496. *
  30497. * @return {Matrix2} The value.
  30498. */
  30499. getValue() {
  30500. return this.nodeUniform.value;
  30501. }
  30502. /**
  30503. * Returns the node uniform data type.
  30504. *
  30505. * @return {string} The data type.
  30506. */
  30507. getType() {
  30508. return this.nodeUniform.type;
  30509. }
  30510. }
  30511. /**
  30512. * A special form of Matrix3 uniform binding type.
  30513. * It's value is managed by a node object.
  30514. *
  30515. * @private
  30516. * @augments Matrix3Uniform
  30517. */
  30518. class Matrix3NodeUniform extends Matrix3Uniform {
  30519. /**
  30520. * Constructs a new node-based Matrix3 uniform.
  30521. *
  30522. * @param {NodeUniform} nodeUniform - The node uniform.
  30523. */
  30524. constructor( nodeUniform ) {
  30525. super( nodeUniform.name, nodeUniform.value );
  30526. /**
  30527. * The node uniform.
  30528. *
  30529. * @type {NodeUniform}
  30530. */
  30531. this.nodeUniform = nodeUniform;
  30532. }
  30533. /**
  30534. * Overwritten to return the value of the node uniform.
  30535. *
  30536. * @return {Matrix3} The value.
  30537. */
  30538. getValue() {
  30539. return this.nodeUniform.value;
  30540. }
  30541. /**
  30542. * Returns the node uniform data type.
  30543. *
  30544. * @return {string} The data type.
  30545. */
  30546. getType() {
  30547. return this.nodeUniform.type;
  30548. }
  30549. }
  30550. /**
  30551. * A special form of Matrix4 uniform binding type.
  30552. * It's value is managed by a node object.
  30553. *
  30554. * @private
  30555. * @augments Matrix4Uniform
  30556. */
  30557. class Matrix4NodeUniform extends Matrix4Uniform {
  30558. /**
  30559. * Constructs a new node-based Matrix4 uniform.
  30560. *
  30561. * @param {NodeUniform} nodeUniform - The node uniform.
  30562. */
  30563. constructor( nodeUniform ) {
  30564. super( nodeUniform.name, nodeUniform.value );
  30565. /**
  30566. * The node uniform.
  30567. *
  30568. * @type {NodeUniform}
  30569. */
  30570. this.nodeUniform = nodeUniform;
  30571. }
  30572. /**
  30573. * Overwritten to return the value of the node uniform.
  30574. *
  30575. * @return {Matrix4} The value.
  30576. */
  30577. getValue() {
  30578. return this.nodeUniform.value;
  30579. }
  30580. /**
  30581. * Returns the node uniform data type.
  30582. *
  30583. * @return {string} The data type.
  30584. */
  30585. getType() {
  30586. return this.nodeUniform.type;
  30587. }
  30588. }
  30589. const rendererCache = new WeakMap();
  30590. const typeFromArray = new Map( [
  30591. [ Int8Array, 'int' ],
  30592. [ Int16Array, 'int' ],
  30593. [ Int32Array, 'int' ],
  30594. [ Uint8Array, 'uint' ],
  30595. [ Uint16Array, 'uint' ],
  30596. [ Uint32Array, 'uint' ],
  30597. [ Float32Array, 'float' ]
  30598. ] );
  30599. const toFloat = ( value ) => {
  30600. if ( /e/g.test( value ) ) {
  30601. return String( value ).replace( /\+/g, '' );
  30602. } else {
  30603. value = Number( value );
  30604. return value + ( value % 1 ? '' : '.0' );
  30605. }
  30606. };
  30607. /**
  30608. * Base class for builders which generate a shader program based
  30609. * on a 3D object and its node material definition.
  30610. */
  30611. class NodeBuilder {
  30612. /**
  30613. * Constructs a new node builder.
  30614. *
  30615. * @param {Object3D} object - The 3D object.
  30616. * @param {Renderer} renderer - The current renderer.
  30617. * @param {NodeParser} parser - A reference to a node parser.
  30618. */
  30619. constructor( object, renderer, parser ) {
  30620. /**
  30621. * The 3D object.
  30622. *
  30623. * @type {Object3D}
  30624. */
  30625. this.object = object;
  30626. /**
  30627. * The material of the 3D object.
  30628. *
  30629. * @type {?Material}
  30630. */
  30631. this.material = ( object && object.material ) || null;
  30632. /**
  30633. * The geometry of the 3D object.
  30634. *
  30635. * @type {?BufferGeometry}
  30636. */
  30637. this.geometry = ( object && object.geometry ) || null;
  30638. /**
  30639. * The current renderer.
  30640. *
  30641. * @type {Renderer}
  30642. */
  30643. this.renderer = renderer;
  30644. /**
  30645. * A reference to a node parser.
  30646. *
  30647. * @type {NodeParser}
  30648. */
  30649. this.parser = parser;
  30650. /**
  30651. * The scene the 3D object belongs to.
  30652. *
  30653. * @type {?Scene}
  30654. * @default null
  30655. */
  30656. this.scene = null;
  30657. /**
  30658. * The camera the 3D object is rendered with.
  30659. *
  30660. * @type {?Camera}
  30661. * @default null
  30662. */
  30663. this.camera = null;
  30664. /**
  30665. * A list of all nodes the builder is processing
  30666. * for this 3D object.
  30667. *
  30668. * @type {Array<Node>}
  30669. */
  30670. this.nodes = [];
  30671. /**
  30672. * A list of all sequential nodes.
  30673. *
  30674. * @type {Array<Node>}
  30675. */
  30676. this.sequentialNodes = [];
  30677. /**
  30678. * A list of all nodes which {@link Node#update} method should be executed.
  30679. *
  30680. * @type {Array<Node>}
  30681. */
  30682. this.updateNodes = [];
  30683. /**
  30684. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  30685. *
  30686. * @type {Array<Node>}
  30687. */
  30688. this.updateBeforeNodes = [];
  30689. /**
  30690. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  30691. *
  30692. * @type {Array<Node>}
  30693. */
  30694. this.updateAfterNodes = [];
  30695. /**
  30696. * A dictionary that assigns each node to a unique hash.
  30697. *
  30698. * @type {Object<number,Node>}
  30699. */
  30700. this.hashNodes = {};
  30701. /**
  30702. * A reference to a node material observer.
  30703. *
  30704. * @type {?NodeMaterialObserver}
  30705. * @default null
  30706. */
  30707. this.observer = null;
  30708. /**
  30709. * A reference to the current lights node.
  30710. *
  30711. * @type {?LightsNode}
  30712. * @default null
  30713. */
  30714. this.lightsNode = null;
  30715. /**
  30716. * A reference to the current environment node.
  30717. *
  30718. * @type {?Node}
  30719. * @default null
  30720. */
  30721. this.environmentNode = null;
  30722. /**
  30723. * A reference to the current fog node.
  30724. *
  30725. * @type {?FogNode}
  30726. * @default null
  30727. */
  30728. this.fogNode = null;
  30729. /**
  30730. * The current clipping context.
  30731. *
  30732. * @type {?ClippingContext}
  30733. */
  30734. this.clippingContext = null;
  30735. /**
  30736. * The generated vertex shader.
  30737. *
  30738. * @type {?string}
  30739. */
  30740. this.vertexShader = null;
  30741. /**
  30742. * The generated fragment shader.
  30743. *
  30744. * @type {?string}
  30745. */
  30746. this.fragmentShader = null;
  30747. /**
  30748. * The generated compute shader.
  30749. *
  30750. * @type {?string}
  30751. */
  30752. this.computeShader = null;
  30753. /**
  30754. * Nodes used in the primary flow of code generation.
  30755. *
  30756. * @type {Object<string,Array<Node>>}
  30757. */
  30758. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  30759. /**
  30760. * Nodes code from `.flowNodes`.
  30761. *
  30762. * @type {Object<string,string>}
  30763. */
  30764. this.flowCode = { vertex: '', fragment: '', compute: '' };
  30765. /**
  30766. * This dictionary holds the node uniforms of the builder.
  30767. * The uniforms are maintained in an array for each shader stage.
  30768. *
  30769. * @type {Object}
  30770. */
  30771. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  30772. /**
  30773. * This dictionary holds the output structs of the builder.
  30774. * The structs are maintained in an array for each shader stage.
  30775. *
  30776. * @type {Object}
  30777. */
  30778. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  30779. /**
  30780. * This dictionary holds the bindings for each shader stage.
  30781. *
  30782. * @type {Object}
  30783. */
  30784. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  30785. /**
  30786. * This dictionary maintains the binding indices per bind group.
  30787. *
  30788. * @type {Object}
  30789. */
  30790. this.bindingsIndexes = {};
  30791. /**
  30792. * Reference to the array of bind groups.
  30793. *
  30794. * @type {?Array<BindGroup>}
  30795. */
  30796. this.bindGroups = null;
  30797. /**
  30798. * This array holds the node attributes of this builder
  30799. * created via {@link AttributeNode}.
  30800. *
  30801. * @type {Array<NodeAttribute>}
  30802. */
  30803. this.attributes = [];
  30804. /**
  30805. * This array holds the node attributes of this builder
  30806. * created via {@link BufferAttributeNode}.
  30807. *
  30808. * @type {Array<NodeAttribute>}
  30809. */
  30810. this.bufferAttributes = [];
  30811. /**
  30812. * This array holds the node varyings of this builder.
  30813. *
  30814. * @type {Array<NodeVarying>}
  30815. */
  30816. this.varyings = [];
  30817. /**
  30818. * This dictionary holds the (native) node codes of this builder.
  30819. * The codes are maintained in an array for each shader stage.
  30820. *
  30821. * @type {Object<string,Array<NodeCode>>}
  30822. */
  30823. this.codes = {};
  30824. /**
  30825. * This dictionary holds the node variables of this builder.
  30826. * The variables are maintained in an array for each shader stage.
  30827. * This dictionary is also used to count the number of variables
  30828. * according to their type (const, vars).
  30829. *
  30830. * @type {Object<string,Array<NodeVar>|number>}
  30831. */
  30832. this.vars = {};
  30833. /**
  30834. * Current code flow.
  30835. * All code generated in this stack will be stored in `.flow`.
  30836. *
  30837. * @type {{code: string}}
  30838. */
  30839. this.flow = { code: '' };
  30840. /**
  30841. * A chain of nodes.
  30842. * Used to check recursive calls in node-graph.
  30843. *
  30844. * @type {Array<Node>}
  30845. */
  30846. this.chaining = [];
  30847. /**
  30848. * The current stack.
  30849. * This reflects the current process in the code block hierarchy,
  30850. * it is useful to know if the current process is inside a conditional for example.
  30851. *
  30852. * @type {StackNode}
  30853. */
  30854. this.stack = stack();
  30855. /**
  30856. * List of stack nodes.
  30857. * The current stack hierarchy is stored in an array.
  30858. *
  30859. * @type {Array<StackNode>}
  30860. */
  30861. this.stacks = [];
  30862. /**
  30863. * A tab value. Used for shader string generation.
  30864. *
  30865. * @type {string}
  30866. * @default '\t'
  30867. */
  30868. this.tab = '\t';
  30869. /**
  30870. * Reference to the current function node.
  30871. *
  30872. * @type {?FunctionNode}
  30873. * @default null
  30874. */
  30875. this.currentFunctionNode = null;
  30876. /**
  30877. * The builder's context.
  30878. *
  30879. * @type {Object}
  30880. */
  30881. this.context = {
  30882. material: this.material
  30883. };
  30884. /**
  30885. * The builder's cache.
  30886. *
  30887. * @type {NodeCache}
  30888. */
  30889. this.cache = new NodeCache();
  30890. /**
  30891. * Since the {@link NodeBuilder#cache} might be temporarily
  30892. * overwritten by other caches, this member retains the reference
  30893. * to the builder's own cache.
  30894. *
  30895. * @type {NodeCache}
  30896. * @default this.cache
  30897. */
  30898. this.globalCache = this.cache;
  30899. this.flowsData = new WeakMap();
  30900. /**
  30901. * The current shader stage.
  30902. *
  30903. * @type {?('vertex'|'fragment'|'compute'|'any')}
  30904. */
  30905. this.shaderStage = null;
  30906. /**
  30907. * The current build stage.
  30908. *
  30909. * @type {?('setup'|'analyze'|'generate')}
  30910. */
  30911. this.buildStage = null;
  30912. /**
  30913. * Whether comparison in shader code are generated with methods or not.
  30914. *
  30915. * @type {boolean}
  30916. * @default false
  30917. */
  30918. this.useComparisonMethod = false;
  30919. }
  30920. /**
  30921. * Returns the bind groups of the current renderer.
  30922. *
  30923. * @return {ChainMap} The cache.
  30924. */
  30925. getBindGroupsCache() {
  30926. let bindGroupsCache = rendererCache.get( this.renderer );
  30927. if ( bindGroupsCache === undefined ) {
  30928. bindGroupsCache = new ChainMap();
  30929. rendererCache.set( this.renderer, bindGroupsCache );
  30930. }
  30931. return bindGroupsCache;
  30932. }
  30933. /**
  30934. * Factory method for creating an instance of {@link RenderTarget} with the given
  30935. * dimensions and options.
  30936. *
  30937. * @param {number} width - The width of the render target.
  30938. * @param {number} height - The height of the render target.
  30939. * @param {Object} options - The options of the render target.
  30940. * @return {RenderTarget} The render target.
  30941. */
  30942. createRenderTarget( width, height, options ) {
  30943. return new RenderTarget( width, height, options );
  30944. }
  30945. /**
  30946. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  30947. * dimensions and options.
  30948. *
  30949. * @param {number} size - The size of the cube render target.
  30950. * @param {Object} options - The options of the cube render target.
  30951. * @return {CubeRenderTarget} The cube render target.
  30952. */
  30953. createCubeRenderTarget( size, options ) {
  30954. return new CubeRenderTarget( size, options );
  30955. }
  30956. /**
  30957. * Whether the given node is included in the internal array of nodes or not.
  30958. *
  30959. * @param {Node} node - The node to test.
  30960. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  30961. */
  30962. includes( node ) {
  30963. return this.nodes.includes( node );
  30964. }
  30965. /**
  30966. * Returns the output struct name which is required by
  30967. * {@link OutputStructNode}.
  30968. *
  30969. * @abstract
  30970. * @return {string} The name of the output struct.
  30971. */
  30972. getOutputStructName() {}
  30973. /**
  30974. * Returns a bind group for the given group name and binding.
  30975. *
  30976. * @private
  30977. * @param {string} groupName - The group name.
  30978. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  30979. * @return {BindGroup} The bind group
  30980. */
  30981. _getBindGroup( groupName, bindings ) {
  30982. const bindGroupsCache = this.getBindGroupsCache();
  30983. //
  30984. const bindingsArray = [];
  30985. let sharedGroup = true;
  30986. for ( const binding of bindings ) {
  30987. bindingsArray.push( binding );
  30988. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  30989. }
  30990. //
  30991. let bindGroup;
  30992. if ( sharedGroup ) {
  30993. bindGroup = bindGroupsCache.get( bindingsArray );
  30994. if ( bindGroup === undefined ) {
  30995. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  30996. bindGroupsCache.set( bindingsArray, bindGroup );
  30997. }
  30998. } else {
  30999. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31000. }
  31001. return bindGroup;
  31002. }
  31003. /**
  31004. * Returns an array of node uniform groups for the given group name and shader stage.
  31005. *
  31006. * @param {string} groupName - The group name.
  31007. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31008. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  31009. */
  31010. getBindGroupArray( groupName, shaderStage ) {
  31011. const bindings = this.bindings[ shaderStage ];
  31012. let bindGroup = bindings[ groupName ];
  31013. if ( bindGroup === undefined ) {
  31014. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  31015. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  31016. }
  31017. bindings[ groupName ] = bindGroup = [];
  31018. }
  31019. return bindGroup;
  31020. }
  31021. /**
  31022. * Returns a list bindings of all shader stages separated by groups.
  31023. *
  31024. * @return {Array<BindGroup>} The list of bindings.
  31025. */
  31026. getBindings() {
  31027. let bindingsGroups = this.bindGroups;
  31028. if ( bindingsGroups === null ) {
  31029. const groups = {};
  31030. const bindings = this.bindings;
  31031. for ( const shaderStage of shaderStages ) {
  31032. for ( const groupName in bindings[ shaderStage ] ) {
  31033. const uniforms = bindings[ shaderStage ][ groupName ];
  31034. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  31035. groupUniforms.push( ...uniforms );
  31036. }
  31037. }
  31038. bindingsGroups = [];
  31039. for ( const groupName in groups ) {
  31040. const group = groups[ groupName ];
  31041. const bindingsGroup = this._getBindGroup( groupName, group );
  31042. bindingsGroups.push( bindingsGroup );
  31043. }
  31044. this.bindGroups = bindingsGroups;
  31045. }
  31046. return bindingsGroups;
  31047. }
  31048. /**
  31049. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  31050. */
  31051. sortBindingGroups() {
  31052. const bindingsGroups = this.getBindings();
  31053. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  31054. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  31055. const bindingGroup = bindingsGroups[ i ];
  31056. this.bindingsIndexes[ bindingGroup.name ].group = i;
  31057. bindingGroup.index = i;
  31058. }
  31059. }
  31060. /**
  31061. * The builder maintains each node in a hash-based dictionary.
  31062. * This method sets the given node (value) with the given hash (key) into this dictionary.
  31063. *
  31064. * @param {Node} node - The node to add.
  31065. * @param {number} hash - The hash of the node.
  31066. */
  31067. setHashNode( node, hash ) {
  31068. this.hashNodes[ hash ] = node;
  31069. }
  31070. /**
  31071. * Adds a node to this builder.
  31072. *
  31073. * @param {Node} node - The node to add.
  31074. */
  31075. addNode( node ) {
  31076. if ( this.nodes.includes( node ) === false ) {
  31077. this.nodes.push( node );
  31078. this.setHashNode( node, node.getHash( this ) );
  31079. }
  31080. }
  31081. /**
  31082. * It is used to add Nodes that will be used as FRAME and RENDER events,
  31083. * and need to follow a certain sequence in the calls to work correctly.
  31084. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  31085. *
  31086. * @param {Node} node - The node to add.
  31087. */
  31088. addSequentialNode( node ) {
  31089. if ( this.sequentialNodes.includes( node ) === false ) {
  31090. this.sequentialNodes.push( node );
  31091. }
  31092. }
  31093. /**
  31094. * Checks the update types of nodes
  31095. */
  31096. buildUpdateNodes() {
  31097. for ( const node of this.nodes ) {
  31098. const updateType = node.getUpdateType();
  31099. if ( updateType !== NodeUpdateType.NONE ) {
  31100. this.updateNodes.push( node.getSelf() );
  31101. }
  31102. }
  31103. for ( const node of this.sequentialNodes ) {
  31104. const updateBeforeType = node.getUpdateBeforeType();
  31105. const updateAfterType = node.getUpdateAfterType();
  31106. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  31107. this.updateBeforeNodes.push( node.getSelf() );
  31108. }
  31109. if ( updateAfterType !== NodeUpdateType.NONE ) {
  31110. this.updateAfterNodes.push( node.getSelf() );
  31111. }
  31112. }
  31113. }
  31114. /**
  31115. * A reference the current node which is the
  31116. * last node in the chain of nodes.
  31117. *
  31118. * @type {Node}
  31119. */
  31120. get currentNode() {
  31121. return this.chaining[ this.chaining.length - 1 ];
  31122. }
  31123. /**
  31124. * Whether the given texture is filtered or not.
  31125. *
  31126. * @param {Texture} texture - The texture to check.
  31127. * @return {boolean} Whether the given texture is filtered or not.
  31128. */
  31129. isFilteredTexture( texture ) {
  31130. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  31131. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  31132. }
  31133. /**
  31134. * Adds the given node to the internal node chain.
  31135. * This is used to check recursive calls in node-graph.
  31136. *
  31137. * @param {Node} node - The node to add.
  31138. */
  31139. addChain( node ) {
  31140. /*
  31141. if ( this.chaining.indexOf( node ) !== - 1 ) {
  31142. console.warn( 'Recursive node: ', node );
  31143. }
  31144. */
  31145. this.chaining.push( node );
  31146. }
  31147. /**
  31148. * Removes the given node from the internal node chain.
  31149. *
  31150. * @param {Node} node - The node to remove.
  31151. */
  31152. removeChain( node ) {
  31153. const lastChain = this.chaining.pop();
  31154. if ( lastChain !== node ) {
  31155. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  31156. }
  31157. }
  31158. /**
  31159. * Returns the native shader method name for a given generic name. E.g.
  31160. * the method name `textureDimensions` matches the WGSL name but must be
  31161. * resolved to `textureSize` in GLSL.
  31162. *
  31163. * @abstract
  31164. * @param {string} method - The method name to resolve.
  31165. * @return {string} The resolved method name.
  31166. */
  31167. getMethod( method ) {
  31168. return method;
  31169. }
  31170. /**
  31171. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  31172. *
  31173. * @param {number} hash - The hash of the node.
  31174. * @return {Node} The found node.
  31175. */
  31176. getNodeFromHash( hash ) {
  31177. return this.hashNodes[ hash ];
  31178. }
  31179. /**
  31180. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  31181. *
  31182. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  31183. * @param {Node} node - The node to add.
  31184. * @return {Node} The node.
  31185. */
  31186. addFlow( shaderStage, node ) {
  31187. this.flowNodes[ shaderStage ].push( node );
  31188. return node;
  31189. }
  31190. /**
  31191. * Sets builder's context.
  31192. *
  31193. * @param {Object} context - The context to set.
  31194. */
  31195. setContext( context ) {
  31196. this.context = context;
  31197. }
  31198. /**
  31199. * Returns the builder's current context.
  31200. *
  31201. * @return {Object} The builder's current context.
  31202. */
  31203. getContext() {
  31204. return this.context;
  31205. }
  31206. /**
  31207. * Gets a context used in shader construction that can be shared across different materials.
  31208. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  31209. *
  31210. * @return {Object} The builder's current context without material.
  31211. */
  31212. getSharedContext() {
  31213. ({ ...this.context });
  31214. return this.context;
  31215. }
  31216. /**
  31217. * Sets builder's cache.
  31218. *
  31219. * @param {NodeCache} cache - The cache to set.
  31220. */
  31221. setCache( cache ) {
  31222. this.cache = cache;
  31223. }
  31224. /**
  31225. * Returns the builder's current cache.
  31226. *
  31227. * @return {NodeCache} The builder's current cache.
  31228. */
  31229. getCache() {
  31230. return this.cache;
  31231. }
  31232. /**
  31233. * Returns a cache for the given node.
  31234. *
  31235. * @param {Node} node - The node.
  31236. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  31237. * @return {NodeCache} The cache.
  31238. */
  31239. getCacheFromNode( node, parent = true ) {
  31240. const data = this.getDataFromNode( node );
  31241. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  31242. return data.cache;
  31243. }
  31244. /**
  31245. * Whether the requested feature is available or not.
  31246. *
  31247. * @abstract
  31248. * @param {string} name - The requested feature.
  31249. * @return {boolean} Whether the requested feature is supported or not.
  31250. */
  31251. isAvailable( /*name*/ ) {
  31252. return false;
  31253. }
  31254. /**
  31255. * Returns the vertexIndex input variable as a native shader string.
  31256. *
  31257. * @abstract
  31258. * @return {string} The instanceIndex shader string.
  31259. */
  31260. getVertexIndex() {
  31261. console.warn( 'Abstract function.' );
  31262. }
  31263. /**
  31264. * Returns the instanceIndex input variable as a native shader string.
  31265. *
  31266. * @abstract
  31267. * @return {string} The instanceIndex shader string.
  31268. */
  31269. getInstanceIndex() {
  31270. console.warn( 'Abstract function.' );
  31271. }
  31272. /**
  31273. * Returns the drawIndex input variable as a native shader string.
  31274. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  31275. *
  31276. * @abstract
  31277. * @return {?string} The drawIndex shader string.
  31278. */
  31279. getDrawIndex() {
  31280. console.warn( 'Abstract function.' );
  31281. }
  31282. /**
  31283. * Returns the frontFacing input variable as a native shader string.
  31284. *
  31285. * @abstract
  31286. * @return {string} The frontFacing shader string.
  31287. */
  31288. getFrontFacing() {
  31289. console.warn( 'Abstract function.' );
  31290. }
  31291. /**
  31292. * Returns the fragCoord input variable as a native shader string.
  31293. *
  31294. * @abstract
  31295. * @return {string} The fragCoord shader string.
  31296. */
  31297. getFragCoord() {
  31298. console.warn( 'Abstract function.' );
  31299. }
  31300. /**
  31301. * Whether to flip texture data along its vertical axis or not. WebGL needs
  31302. * this method evaluate to `true`, WebGPU to `false`.
  31303. *
  31304. * @abstract
  31305. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  31306. */
  31307. isFlipY() {
  31308. return false;
  31309. }
  31310. /**
  31311. * Calling this method increases the usage count for the given node by one.
  31312. *
  31313. * @param {Node} node - The node to increase the usage count for.
  31314. * @return {number} The updated usage count.
  31315. */
  31316. increaseUsage( node ) {
  31317. const nodeData = this.getDataFromNode( node );
  31318. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  31319. return nodeData.usageCount;
  31320. }
  31321. /**
  31322. * Generates a texture sample shader string for the given texture data.
  31323. *
  31324. * @abstract
  31325. * @param {Texture} texture - The texture.
  31326. * @param {string} textureProperty - The texture property name.
  31327. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  31328. * @return {string} The generated shader string.
  31329. */
  31330. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  31331. console.warn( 'Abstract function.' );
  31332. }
  31333. /**
  31334. * Generates a texture LOD shader string for the given texture data.
  31335. *
  31336. * @abstract
  31337. * @param {Texture} texture - The texture.
  31338. * @param {string} textureProperty - The texture property name.
  31339. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  31340. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  31341. * @param {string} levelSnippet - Snippet defining the mip level.
  31342. * @return {string} The generated shader string.
  31343. */
  31344. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  31345. console.warn( 'Abstract function.' );
  31346. }
  31347. /**
  31348. * Generates the array declaration string.
  31349. *
  31350. * @param {string} type - The type.
  31351. * @param {?number} [count] - The count.
  31352. * @return {string} The generated value as a shader string.
  31353. */
  31354. generateArrayDeclaration( type, count ) {
  31355. return this.getType( type ) + '[ ' + count + ' ]';
  31356. }
  31357. /**
  31358. * Generates the array shader string for the given type and value.
  31359. *
  31360. * @param {string} type - The type.
  31361. * @param {?number} [count] - The count.
  31362. * @param {?Array<Node>} [values=null] - The default values.
  31363. * @return {string} The generated value as a shader string.
  31364. */
  31365. generateArray( type, count, values = null ) {
  31366. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  31367. for ( let i = 0; i < count; i ++ ) {
  31368. const value = values ? values[ i ] : null;
  31369. if ( value !== null ) {
  31370. snippet += value.build( this, type );
  31371. } else {
  31372. snippet += this.generateConst( type );
  31373. }
  31374. if ( i < count - 1 ) snippet += ', ';
  31375. }
  31376. snippet += ' )';
  31377. return snippet;
  31378. }
  31379. /**
  31380. * Generates the struct shader string.
  31381. *
  31382. * @param {string} type - The type.
  31383. * @param {Array<Object>} [membersLayout] - The count.
  31384. * @param {?Array<Node>} [values=null] - The default values.
  31385. * @return {string} The generated value as a shader string.
  31386. */
  31387. generateStruct( type, membersLayout, values = null ) {
  31388. const snippets = [];
  31389. for ( const member of membersLayout ) {
  31390. const { name, type } = member;
  31391. if ( values && values[ name ] && values[ name ].isNode ) {
  31392. snippets.push( values[ name ].build( this, type ) );
  31393. } else {
  31394. snippets.push( this.generateConst( type ) );
  31395. }
  31396. }
  31397. return type + '( ' + snippets.join( ', ' ) + ' )';
  31398. }
  31399. /**
  31400. * Generates the shader string for the given type and value.
  31401. *
  31402. * @param {string} type - The type.
  31403. * @param {?any} [value=null] - The value.
  31404. * @return {string} The generated value as a shader string.
  31405. */
  31406. generateConst( type, value = null ) {
  31407. if ( value === null ) {
  31408. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  31409. else if ( type === 'bool' ) value = false;
  31410. else if ( type === 'color' ) value = new Color();
  31411. else if ( type === 'vec2' ) value = new Vector2();
  31412. else if ( type === 'vec3' ) value = new Vector3();
  31413. else if ( type === 'vec4' ) value = new Vector4();
  31414. }
  31415. if ( type === 'float' ) return toFloat( value );
  31416. if ( type === 'int' ) return `${ Math.round( value ) }`;
  31417. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  31418. if ( type === 'bool' ) return value ? 'true' : 'false';
  31419. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  31420. const typeLength = this.getTypeLength( type );
  31421. const componentType = this.getComponentType( type );
  31422. const generateConst = value => this.generateConst( componentType, value );
  31423. if ( typeLength === 2 ) {
  31424. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  31425. } else if ( typeLength === 3 ) {
  31426. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  31427. } else if ( typeLength === 4 && type !== 'mat2' ) {
  31428. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  31429. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  31430. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  31431. } else if ( typeLength > 4 ) {
  31432. return `${ this.getType( type ) }()`;
  31433. }
  31434. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  31435. }
  31436. /**
  31437. * It might be necessary to convert certain data types to different ones
  31438. * so this method can be used to hide the conversion.
  31439. *
  31440. * @param {string} type - The type.
  31441. * @return {string} The updated type.
  31442. */
  31443. getType( type ) {
  31444. if ( type === 'color' ) return 'vec3';
  31445. return type;
  31446. }
  31447. /**
  31448. * Whether the given attribute name is defined in the geometry or not.
  31449. *
  31450. * @param {string} name - The attribute name.
  31451. * @return {boolean} Whether the given attribute name is defined in the geometry.
  31452. */
  31453. hasGeometryAttribute( name ) {
  31454. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  31455. }
  31456. /**
  31457. * Returns a node attribute for the given name and type.
  31458. *
  31459. * @param {string} name - The attribute's name.
  31460. * @param {string} type - The attribute's type.
  31461. * @return {NodeAttribute} The node attribute.
  31462. */
  31463. getAttribute( name, type ) {
  31464. const attributes = this.attributes;
  31465. // find attribute
  31466. for ( const attribute of attributes ) {
  31467. if ( attribute.name === name ) {
  31468. return attribute;
  31469. }
  31470. }
  31471. // create a new if no exist
  31472. const attribute = new NodeAttribute( name, type );
  31473. attributes.push( attribute );
  31474. return attribute;
  31475. }
  31476. /**
  31477. * Returns for the given node and shader stage the property name for the shader.
  31478. *
  31479. * @param {Node} node - The node.
  31480. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31481. * @return {string} The property name.
  31482. */
  31483. getPropertyName( node/*, shaderStage*/ ) {
  31484. return node.name;
  31485. }
  31486. /**
  31487. * Whether the given type is a vector type or not.
  31488. *
  31489. * @param {string} type - The type to check.
  31490. * @return {boolean} Whether the given type is a vector type or not.
  31491. */
  31492. isVector( type ) {
  31493. return /vec\d/.test( type );
  31494. }
  31495. /**
  31496. * Whether the given type is a matrix type or not.
  31497. *
  31498. * @param {string} type - The type to check.
  31499. * @return {boolean} Whether the given type is a matrix type or not.
  31500. */
  31501. isMatrix( type ) {
  31502. return /mat\d/.test( type );
  31503. }
  31504. /**
  31505. * Whether the given type is a reference type or not.
  31506. *
  31507. * @param {string} type - The type to check.
  31508. * @return {boolean} Whether the given type is a reference type or not.
  31509. */
  31510. isReference( type ) {
  31511. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  31512. }
  31513. /**
  31514. * Checks if the given texture requires a manual conversion to the working color space.
  31515. *
  31516. * @abstract
  31517. * @param {Texture} texture - The texture to check.
  31518. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  31519. */
  31520. needsToWorkingColorSpace( /*texture*/ ) {
  31521. return false;
  31522. }
  31523. /**
  31524. * Returns the component type of a given texture.
  31525. *
  31526. * @param {Texture} texture - The texture.
  31527. * @return {string} The component type.
  31528. */
  31529. getComponentTypeFromTexture( texture ) {
  31530. const type = texture.type;
  31531. if ( texture.isDataTexture ) {
  31532. if ( type === IntType ) return 'int';
  31533. if ( type === UnsignedIntType ) return 'uint';
  31534. }
  31535. return 'float';
  31536. }
  31537. /**
  31538. * Returns the element type for a given type.
  31539. *
  31540. * @param {string} type - The type.
  31541. * @return {string} The element type.
  31542. */
  31543. getElementType( type ) {
  31544. if ( type === 'mat2' ) return 'vec2';
  31545. if ( type === 'mat3' ) return 'vec3';
  31546. if ( type === 'mat4' ) return 'vec4';
  31547. return this.getComponentType( type );
  31548. }
  31549. /**
  31550. * Returns the component type for a given type.
  31551. *
  31552. * @param {string} type - The type.
  31553. * @return {string} The component type.
  31554. */
  31555. getComponentType( type ) {
  31556. type = this.getVectorType( type );
  31557. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  31558. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  31559. if ( componentType === null ) return null;
  31560. if ( componentType[ 1 ] === 'b' ) return 'bool';
  31561. if ( componentType[ 1 ] === 'i' ) return 'int';
  31562. if ( componentType[ 1 ] === 'u' ) return 'uint';
  31563. return 'float';
  31564. }
  31565. /**
  31566. * Returns the vector type for a given type.
  31567. *
  31568. * @param {string} type - The type.
  31569. * @return {string} The vector type.
  31570. */
  31571. getVectorType( type ) {
  31572. if ( type === 'color' ) return 'vec3';
  31573. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  31574. return type;
  31575. }
  31576. /**
  31577. * Returns the data type for the given the length and component type.
  31578. *
  31579. * @param {number} length - The length.
  31580. * @param {string} [componentType='float'] - The component type.
  31581. * @return {string} The type.
  31582. */
  31583. getTypeFromLength( length, componentType = 'float' ) {
  31584. if ( length === 1 ) return componentType;
  31585. let baseType = getTypeFromLength( length );
  31586. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  31587. // fix edge case for mat2x2 being same size as vec4
  31588. if ( /mat2/.test( componentType ) === true ) {
  31589. baseType = baseType.replace( 'vec', 'mat' );
  31590. }
  31591. return prefix + baseType;
  31592. }
  31593. /**
  31594. * Returns the type for a given typed array.
  31595. *
  31596. * @param {TypedArray} array - The typed array.
  31597. * @return {string} The type.
  31598. */
  31599. getTypeFromArray( array ) {
  31600. return typeFromArray.get( array.constructor );
  31601. }
  31602. /**
  31603. * Returns the type for a given buffer attribute.
  31604. *
  31605. * @param {BufferAttribute} attribute - The buffer attribute.
  31606. * @return {string} The type.
  31607. */
  31608. getTypeFromAttribute( attribute ) {
  31609. let dataAttribute = attribute;
  31610. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  31611. const array = dataAttribute.array;
  31612. const itemSize = attribute.itemSize;
  31613. const normalized = attribute.normalized;
  31614. let arrayType;
  31615. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  31616. arrayType = this.getTypeFromArray( array );
  31617. }
  31618. return this.getTypeFromLength( itemSize, arrayType );
  31619. }
  31620. /**
  31621. * Returns the length for the given data type.
  31622. *
  31623. * @param {string} type - The data type.
  31624. * @return {number} The length.
  31625. */
  31626. getTypeLength( type ) {
  31627. const vecType = this.getVectorType( type );
  31628. const vecNum = /vec([2-4])/.exec( vecType );
  31629. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  31630. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  31631. if ( /mat2/.test( type ) === true ) return 4;
  31632. if ( /mat3/.test( type ) === true ) return 9;
  31633. if ( /mat4/.test( type ) === true ) return 16;
  31634. return 0;
  31635. }
  31636. /**
  31637. * Returns the vector type for a given matrix type.
  31638. *
  31639. * @param {string} type - The matrix type.
  31640. * @return {string} The vector type.
  31641. */
  31642. getVectorFromMatrix( type ) {
  31643. return type.replace( 'mat', 'vec' );
  31644. }
  31645. /**
  31646. * For a given type this method changes the component type to the
  31647. * given value. E.g. `vec4` should be changed to the new component type
  31648. * `uint` which results in `uvec4`.
  31649. *
  31650. * @param {string} type - The type.
  31651. * @param {string} newComponentType - The new component type.
  31652. * @return {string} The new type.
  31653. */
  31654. changeComponentType( type, newComponentType ) {
  31655. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  31656. }
  31657. /**
  31658. * Returns the integer type pendant for the given type.
  31659. *
  31660. * @param {string} type - The type.
  31661. * @return {string} The integer type.
  31662. */
  31663. getIntegerType( type ) {
  31664. const componentType = this.getComponentType( type );
  31665. if ( componentType === 'int' || componentType === 'uint' ) return type;
  31666. return this.changeComponentType( type, 'int' );
  31667. }
  31668. /**
  31669. * Adds a stack node to the internal stack.
  31670. *
  31671. * @return {StackNode} The added stack node.
  31672. */
  31673. addStack() {
  31674. this.stack = stack( this.stack );
  31675. this.stacks.push( getCurrentStack() || this.stack );
  31676. setCurrentStack( this.stack );
  31677. return this.stack;
  31678. }
  31679. /**
  31680. * Removes the last stack node from the internal stack.
  31681. *
  31682. * @return {StackNode} The removed stack node.
  31683. */
  31684. removeStack() {
  31685. const lastStack = this.stack;
  31686. this.stack = lastStack.parent;
  31687. setCurrentStack( this.stacks.pop() );
  31688. return lastStack;
  31689. }
  31690. /**
  31691. * The builder maintains (cached) data for each node during the building process. This method
  31692. * can be used to get these data for a specific shader stage and cache.
  31693. *
  31694. * @param {Node} node - The node to get the data for.
  31695. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31696. * @param {?NodeCache} cache - An optional cache.
  31697. * @return {Object} The node data.
  31698. */
  31699. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  31700. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  31701. let nodeData = cache.getData( node );
  31702. if ( nodeData === undefined ) {
  31703. nodeData = {};
  31704. cache.setData( node, nodeData );
  31705. }
  31706. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  31707. return nodeData[ shaderStage ];
  31708. }
  31709. /**
  31710. * Returns the properties for the given node and shader stage.
  31711. *
  31712. * @param {Node} node - The node to get the properties for.
  31713. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  31714. * @return {Object} The node properties.
  31715. */
  31716. getNodeProperties( node, shaderStage = 'any' ) {
  31717. const nodeData = this.getDataFromNode( node, shaderStage );
  31718. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  31719. }
  31720. /**
  31721. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  31722. *
  31723. * @param {BufferAttributeNode} node - The buffer attribute node.
  31724. * @param {string} type - The node type.
  31725. * @return {NodeAttribute} The node attribute.
  31726. */
  31727. getBufferAttributeFromNode( node, type ) {
  31728. const nodeData = this.getDataFromNode( node );
  31729. let bufferAttribute = nodeData.bufferAttribute;
  31730. if ( bufferAttribute === undefined ) {
  31731. const index = this.uniforms.index ++;
  31732. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  31733. this.bufferAttributes.push( bufferAttribute );
  31734. nodeData.bufferAttribute = bufferAttribute;
  31735. }
  31736. return bufferAttribute;
  31737. }
  31738. /**
  31739. * Returns an instance of {@link StructType} for the given output struct node.
  31740. *
  31741. * @param {OutputStructNode} node - The output struct node.
  31742. * @param {Array<Object>} membersLayout - The output struct types.
  31743. * @param {?string} [name=null] - The name of the struct.
  31744. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31745. * @return {StructType} The struct type attribute.
  31746. */
  31747. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  31748. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31749. let structType = nodeData.structType;
  31750. if ( structType === undefined ) {
  31751. const index = this.structs.index ++;
  31752. if ( name === null ) name = 'StructType' + index;
  31753. structType = new StructType( name, membersLayout );
  31754. this.structs[ shaderStage ].push( structType );
  31755. nodeData.structType = structType;
  31756. }
  31757. return structType;
  31758. }
  31759. /**
  31760. * Returns an instance of {@link StructType} for the given output struct node.
  31761. *
  31762. * @param {OutputStructNode} node - The output struct node.
  31763. * @param {Array<Object>} membersLayout - The output struct types.
  31764. * @return {StructType} The struct type attribute.
  31765. */
  31766. getOutputStructTypeFromNode( node, membersLayout ) {
  31767. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  31768. structType.output = true;
  31769. return structType;
  31770. }
  31771. /**
  31772. * Returns an instance of {@link NodeUniform} for the given uniform node.
  31773. *
  31774. * @param {UniformNode} node - The uniform node.
  31775. * @param {string} type - The uniform type.
  31776. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31777. * @param {?string} name - The name of the uniform.
  31778. * @return {NodeUniform} The node uniform.
  31779. */
  31780. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  31781. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31782. let nodeUniform = nodeData.uniform;
  31783. if ( nodeUniform === undefined ) {
  31784. const index = this.uniforms.index ++;
  31785. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  31786. this.uniforms[ shaderStage ].push( nodeUniform );
  31787. nodeData.uniform = nodeUniform;
  31788. }
  31789. return nodeUniform;
  31790. }
  31791. /**
  31792. * Returns the array length.
  31793. *
  31794. * @param {Node} node - The node.
  31795. * @return {?number} The array length.
  31796. */
  31797. getArrayCount( node ) {
  31798. let count = null;
  31799. if ( node.isArrayNode ) count = node.count;
  31800. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  31801. return count;
  31802. }
  31803. /**
  31804. * Returns an instance of {@link NodeVar} for the given variable node.
  31805. *
  31806. * @param {VarNode} node - The variable node.
  31807. * @param {?string} name - The variable's name.
  31808. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  31809. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31810. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  31811. *
  31812. * @return {NodeVar} The node variable.
  31813. */
  31814. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  31815. const nodeData = this.getDataFromNode( node, shaderStage );
  31816. let nodeVar = nodeData.variable;
  31817. if ( nodeVar === undefined ) {
  31818. const idNS = readOnly ? '_const' : '_var';
  31819. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  31820. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  31821. if ( name === null ) {
  31822. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  31823. this.vars[ idNS ] ++;
  31824. }
  31825. //
  31826. const count = this.getArrayCount( node );
  31827. nodeVar = new NodeVar( name, type, readOnly, count );
  31828. if ( ! readOnly ) {
  31829. vars.push( nodeVar );
  31830. }
  31831. nodeData.variable = nodeVar;
  31832. }
  31833. return nodeVar;
  31834. }
  31835. /**
  31836. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  31837. *
  31838. * @param {Node} node - The varying node.
  31839. * @return {boolean} Returns true if deterministic.
  31840. */
  31841. isDeterministic( node ) {
  31842. if ( node.isMathNode ) {
  31843. return this.isDeterministic( node.aNode ) &&
  31844. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  31845. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  31846. } else if ( node.isOperatorNode ) {
  31847. return this.isDeterministic( node.aNode ) &&
  31848. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  31849. } else if ( node.isArrayNode ) {
  31850. if ( node.values !== null ) {
  31851. for ( const n of node.values ) {
  31852. if ( ! this.isDeterministic( n ) ) {
  31853. return false;
  31854. }
  31855. }
  31856. }
  31857. return true;
  31858. } else if ( node.isConstNode ) {
  31859. return true;
  31860. }
  31861. return false;
  31862. }
  31863. /**
  31864. * Returns an instance of {@link NodeVarying} for the given varying node.
  31865. *
  31866. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  31867. * @param {?string} name - The varying's name.
  31868. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  31869. * @return {NodeVar} The node varying.
  31870. */
  31871. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  31872. const nodeData = this.getDataFromNode( node, 'any' );
  31873. let nodeVarying = nodeData.varying;
  31874. if ( nodeVarying === undefined ) {
  31875. const varyings = this.varyings;
  31876. const index = varyings.length;
  31877. if ( name === null ) name = 'nodeVarying' + index;
  31878. nodeVarying = new NodeVarying( name, type );
  31879. varyings.push( nodeVarying );
  31880. nodeData.varying = nodeVarying;
  31881. }
  31882. return nodeVarying;
  31883. }
  31884. /**
  31885. * Returns an instance of {@link NodeCode} for the given code node.
  31886. *
  31887. * @param {CodeNode} node - The code node.
  31888. * @param {string} type - The node type.
  31889. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  31890. * @return {NodeCode} The node code.
  31891. */
  31892. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31893. const nodeData = this.getDataFromNode( node );
  31894. let nodeCode = nodeData.code;
  31895. if ( nodeCode === undefined ) {
  31896. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31897. const index = codes.length;
  31898. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31899. codes.push( nodeCode );
  31900. nodeData.code = nodeCode;
  31901. }
  31902. return nodeCode;
  31903. }
  31904. /**
  31905. * Adds a code flow based on the code-block hierarchy.
  31906. * This is used so that code-blocks like If,Else create their variables locally if the Node
  31907. * is only used inside one of these conditionals in the current shader stage.
  31908. *
  31909. * @param {Node} node - The node to add.
  31910. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  31911. */
  31912. addFlowCodeHierarchy( node, nodeBlock ) {
  31913. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31914. let needsFlowCode = true;
  31915. let nodeBlockHierarchy = nodeBlock;
  31916. while ( nodeBlockHierarchy ) {
  31917. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31918. needsFlowCode = false;
  31919. break;
  31920. }
  31921. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31922. }
  31923. if ( needsFlowCode ) {
  31924. for ( const flowCode of flowCodes ) {
  31925. this.addLineFlowCode( flowCode );
  31926. }
  31927. }
  31928. }
  31929. /**
  31930. * Add a inline-code to the current flow code-block.
  31931. *
  31932. * @param {Node} node - The node to add.
  31933. * @param {string} code - The code to add.
  31934. * @param {Node} nodeBlock - Current ConditionalNode
  31935. */
  31936. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31937. const nodeData = this.getDataFromNode( node );
  31938. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31939. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31940. flowCodes.push( code );
  31941. codeBlock.set( nodeBlock, true );
  31942. }
  31943. /**
  31944. * Add a inline-code to the current flow.
  31945. *
  31946. * @param {string} code - The code to add.
  31947. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  31948. * @return {NodeBuilder} A reference to this node builder.
  31949. */
  31950. addLineFlowCode( code, node = null ) {
  31951. if ( code === '' ) return this;
  31952. if ( node !== null && this.context.nodeBlock ) {
  31953. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31954. }
  31955. code = this.tab + code;
  31956. if ( ! /;\s*$/.test( code ) ) {
  31957. code = code + ';\n';
  31958. }
  31959. this.flow.code += code;
  31960. return this;
  31961. }
  31962. /**
  31963. * Adds a code to the current code flow.
  31964. *
  31965. * @param {string} code - Shader code.
  31966. * @return {NodeBuilder} A reference to this node builder.
  31967. */
  31968. addFlowCode( code ) {
  31969. this.flow.code += code;
  31970. return this;
  31971. }
  31972. /**
  31973. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  31974. * Typically used in codes with If,Else.
  31975. *
  31976. * @return {NodeBuilder} A reference to this node builder.
  31977. */
  31978. addFlowTab() {
  31979. this.tab += '\t';
  31980. return this;
  31981. }
  31982. /**
  31983. * Removes a tab.
  31984. *
  31985. * @return {NodeBuilder} A reference to this node builder.
  31986. */
  31987. removeFlowTab() {
  31988. this.tab = this.tab.slice( 0, -1 );
  31989. return this;
  31990. }
  31991. /**
  31992. * Gets the current flow data based on a Node.
  31993. *
  31994. * @param {Node} node - Node that the flow was started.
  31995. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31996. * @return {Object} The flow data.
  31997. */
  31998. getFlowData( node/*, shaderStage*/ ) {
  31999. return this.flowsData.get( node );
  32000. }
  32001. /**
  32002. * Executes the node flow based on a root node to generate the final shader code.
  32003. *
  32004. * @param {Node} node - The node to execute.
  32005. * @return {Object} The code flow.
  32006. */
  32007. flowNode( node ) {
  32008. const output = node.getNodeType( this );
  32009. const flowData = this.flowChildNode( node, output );
  32010. this.flowsData.set( node, flowData );
  32011. return flowData;
  32012. }
  32013. /**
  32014. * Includes a node in the current function node.
  32015. *
  32016. * @param {Node} node - The node to include.
  32017. * @returns {void}
  32018. */
  32019. addInclude( node ) {
  32020. if ( this.currentFunctionNode !== null ) {
  32021. this.currentFunctionNode.includes.push( node );
  32022. }
  32023. }
  32024. /**
  32025. * Returns the native shader operator name for a given generic name.
  32026. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  32027. *
  32028. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  32029. * @return {FunctionNode} The build function node.
  32030. */
  32031. buildFunctionNode( shaderNode ) {
  32032. const fn = new FunctionNode();
  32033. const previous = this.currentFunctionNode;
  32034. this.currentFunctionNode = fn;
  32035. fn.code = this.buildFunctionCode( shaderNode );
  32036. this.currentFunctionNode = previous;
  32037. return fn;
  32038. }
  32039. /**
  32040. * Generates a code flow based on a TSL function: Fn().
  32041. *
  32042. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  32043. * @return {Object}
  32044. */
  32045. flowShaderNode( shaderNode ) {
  32046. const layout = shaderNode.layout;
  32047. const inputs = {
  32048. [ Symbol.iterator ]() {
  32049. let index = 0;
  32050. const values = Object.values( this );
  32051. return {
  32052. next: () => ( {
  32053. value: values[ index ],
  32054. done: index ++ >= values.length
  32055. } )
  32056. };
  32057. }
  32058. };
  32059. for ( const input of layout.inputs ) {
  32060. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  32061. }
  32062. //
  32063. shaderNode.layout = null;
  32064. const callNode = shaderNode.call( inputs );
  32065. const flowData = this.flowStagesNode( callNode, layout.type );
  32066. shaderNode.layout = layout;
  32067. return flowData;
  32068. }
  32069. /**
  32070. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  32071. *
  32072. * @param {Node} node - The node to execute.
  32073. * @param {?string} output - Expected output type. For example 'vec3'.
  32074. * @return {Object}
  32075. */
  32076. flowStagesNode( node, output = null ) {
  32077. const previousFlow = this.flow;
  32078. const previousVars = this.vars;
  32079. const previousCache = this.cache;
  32080. const previousBuildStage = this.buildStage;
  32081. const previousStack = this.stack;
  32082. const flow = {
  32083. code: ''
  32084. };
  32085. this.flow = flow;
  32086. this.vars = {};
  32087. this.cache = new NodeCache();
  32088. this.stack = stack();
  32089. for ( const buildStage of defaultBuildStages ) {
  32090. this.setBuildStage( buildStage );
  32091. flow.result = node.build( this, output );
  32092. }
  32093. flow.vars = this.getVars( this.shaderStage );
  32094. this.flow = previousFlow;
  32095. this.vars = previousVars;
  32096. this.cache = previousCache;
  32097. this.stack = previousStack;
  32098. this.setBuildStage( previousBuildStage );
  32099. return flow;
  32100. }
  32101. /**
  32102. * Returns the native shader operator name for a given generic name.
  32103. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  32104. *
  32105. * @abstract
  32106. * @param {string} op - The operator name to resolve.
  32107. * @return {?string} The resolved operator name.
  32108. */
  32109. getFunctionOperator( /* op */ ) {
  32110. return null;
  32111. }
  32112. /**
  32113. * Builds the given shader node.
  32114. *
  32115. * @abstract
  32116. * @param {ShaderNodeInternal} shaderNode - The shader node.
  32117. * @return {string} The function code.
  32118. */
  32119. buildFunctionCode( /* shaderNode */ ) {
  32120. console.warn( 'Abstract function.' );
  32121. }
  32122. /**
  32123. * Generates a code flow based on a child Node.
  32124. *
  32125. * @param {Node} node - The node to execute.
  32126. * @param {?string} output - Expected output type. For example 'vec3'.
  32127. * @return {Object} The code flow.
  32128. */
  32129. flowChildNode( node, output = null ) {
  32130. const previousFlow = this.flow;
  32131. const flow = {
  32132. code: ''
  32133. };
  32134. this.flow = flow;
  32135. flow.result = node.build( this, output );
  32136. this.flow = previousFlow;
  32137. return flow;
  32138. }
  32139. /**
  32140. * Executes a flow of code in a different stage.
  32141. *
  32142. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  32143. * return the value in fragment-stage even if it is being executed in an input fragment.
  32144. *
  32145. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32146. * @param {Node} node - The node to execute.
  32147. * @param {?string} output - Expected output type. For example 'vec3'.
  32148. * @param {?string} propertyName - The property name to assign the result.
  32149. * @return {Object}
  32150. */
  32151. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  32152. const previousShaderStage = this.shaderStage;
  32153. this.setShaderStage( shaderStage );
  32154. const flowData = this.flowChildNode( node, output );
  32155. if ( propertyName !== null ) {
  32156. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  32157. }
  32158. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  32159. this.setShaderStage( previousShaderStage );
  32160. return flowData;
  32161. }
  32162. /**
  32163. * Returns an array holding all node attributes of this node builder.
  32164. *
  32165. * @return {Array<NodeAttribute>} The node attributes of this builder.
  32166. */
  32167. getAttributesArray() {
  32168. return this.attributes.concat( this.bufferAttributes );
  32169. }
  32170. /**
  32171. * Returns the attribute definitions as a shader string for the given shader stage.
  32172. *
  32173. * @abstract
  32174. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32175. * @return {string} The attribute code section.
  32176. */
  32177. getAttributes( /*shaderStage*/ ) {
  32178. console.warn( 'Abstract function.' );
  32179. }
  32180. /**
  32181. * Returns the varying definitions as a shader string for the given shader stage.
  32182. *
  32183. * @abstract
  32184. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32185. * @return {string} The varying code section.
  32186. */
  32187. getVaryings( /*shaderStage*/ ) {
  32188. console.warn( 'Abstract function.' );
  32189. }
  32190. /**
  32191. * Returns a single variable definition as a shader string for the given variable type and name.
  32192. *
  32193. * @param {string} type - The variable's type.
  32194. * @param {string} name - The variable's name.
  32195. * @param {?number} [count=null] - The array length.
  32196. * @return {string} The shader string.
  32197. */
  32198. getVar( type, name, count = null ) {
  32199. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  32200. }
  32201. /**
  32202. * Returns the variable definitions as a shader string for the given shader stage.
  32203. *
  32204. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32205. * @return {string} The variable code section.
  32206. */
  32207. getVars( shaderStage ) {
  32208. let snippet = '';
  32209. const vars = this.vars[ shaderStage ];
  32210. if ( vars !== undefined ) {
  32211. for ( const variable of vars ) {
  32212. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  32213. }
  32214. }
  32215. return snippet;
  32216. }
  32217. /**
  32218. * Returns the uniform definitions as a shader string for the given shader stage.
  32219. *
  32220. * @abstract
  32221. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32222. * @return {string} The uniform code section.
  32223. */
  32224. getUniforms( /*shaderStage*/ ) {
  32225. console.warn( 'Abstract function.' );
  32226. }
  32227. /**
  32228. * Returns the native code definitions as a shader string for the given shader stage.
  32229. *
  32230. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32231. * @return {string} The native code section.
  32232. */
  32233. getCodes( shaderStage ) {
  32234. const codes = this.codes[ shaderStage ];
  32235. let code = '';
  32236. if ( codes !== undefined ) {
  32237. for ( const nodeCode of codes ) {
  32238. code += nodeCode.code + '\n';
  32239. }
  32240. }
  32241. return code;
  32242. }
  32243. /**
  32244. * Returns the hash of this node builder.
  32245. *
  32246. * @return {string} The hash.
  32247. */
  32248. getHash() {
  32249. return this.vertexShader + this.fragmentShader + this.computeShader;
  32250. }
  32251. /**
  32252. * Sets the current shader stage.
  32253. *
  32254. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  32255. */
  32256. setShaderStage( shaderStage ) {
  32257. this.shaderStage = shaderStage;
  32258. }
  32259. /**
  32260. * Returns the current shader stage.
  32261. *
  32262. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  32263. */
  32264. getShaderStage() {
  32265. return this.shaderStage;
  32266. }
  32267. /**
  32268. * Sets the current build stage.
  32269. *
  32270. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  32271. */
  32272. setBuildStage( buildStage ) {
  32273. this.buildStage = buildStage;
  32274. }
  32275. /**
  32276. * Returns the current build stage.
  32277. *
  32278. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  32279. */
  32280. getBuildStage() {
  32281. return this.buildStage;
  32282. }
  32283. /**
  32284. * Controls the code build of the shader stages.
  32285. *
  32286. * @abstract
  32287. */
  32288. buildCode() {
  32289. console.warn( 'Abstract function.' );
  32290. }
  32291. /**
  32292. * Central build method which controls the build for the given object.
  32293. *
  32294. * @return {NodeBuilder} A reference to this node builder.
  32295. */
  32296. build() {
  32297. const { object, material, renderer } = this;
  32298. if ( material !== null ) {
  32299. let nodeMaterial = renderer.library.fromMaterial( material );
  32300. if ( nodeMaterial === null ) {
  32301. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  32302. nodeMaterial = new NodeMaterial();
  32303. }
  32304. nodeMaterial.build( this );
  32305. } else {
  32306. this.addFlow( 'compute', object );
  32307. }
  32308. // setup() -> stage 1: create possible new nodes and returns an output reference node
  32309. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  32310. // generate() -> stage 3: generate shader
  32311. for ( const buildStage of defaultBuildStages ) {
  32312. this.setBuildStage( buildStage );
  32313. if ( this.context.vertex && this.context.vertex.isNode ) {
  32314. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  32315. }
  32316. for ( const shaderStage of shaderStages ) {
  32317. this.setShaderStage( shaderStage );
  32318. const flowNodes = this.flowNodes[ shaderStage ];
  32319. for ( const node of flowNodes ) {
  32320. if ( buildStage === 'generate' ) {
  32321. this.flowNode( node );
  32322. } else {
  32323. node.build( this );
  32324. }
  32325. }
  32326. }
  32327. }
  32328. this.setBuildStage( null );
  32329. this.setShaderStage( null );
  32330. // stage 4: build code for a specific output
  32331. this.buildCode();
  32332. this.buildUpdateNodes();
  32333. return this;
  32334. }
  32335. /**
  32336. * Returns a uniform representation which is later used for UBO generation and rendering.
  32337. *
  32338. * @param {NodeUniform} uniformNode - The uniform node.
  32339. * @param {string} type - The requested type.
  32340. * @return {Uniform} The uniform.
  32341. */
  32342. getNodeUniform( uniformNode, type ) {
  32343. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  32344. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  32345. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  32346. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  32347. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  32348. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  32349. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  32350. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  32351. throw new Error( `Uniform "${type}" not declared.` );
  32352. }
  32353. /**
  32354. * Formats the given shader snippet from a given type into another one. E.g.
  32355. * this method might be used to convert a simple float string `"1.0"` into a
  32356. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  32357. *
  32358. * @param {string} snippet - The shader snippet.
  32359. * @param {string} fromType - The source type.
  32360. * @param {string} toType - The target type.
  32361. * @return {string} The updated shader string.
  32362. */
  32363. format( snippet, fromType, toType ) {
  32364. fromType = this.getVectorType( fromType );
  32365. toType = this.getVectorType( toType );
  32366. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  32367. return snippet;
  32368. }
  32369. const fromTypeLength = this.getTypeLength( fromType );
  32370. const toTypeLength = this.getTypeLength( toType );
  32371. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  32372. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  32373. }
  32374. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  32375. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  32376. }
  32377. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  32378. // @TODO: ignore for now
  32379. return snippet;
  32380. }
  32381. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  32382. // @TODO: ignore for now
  32383. return snippet;
  32384. }
  32385. if ( fromTypeLength === toTypeLength ) {
  32386. return `${ this.getType( toType ) }( ${ snippet } )`;
  32387. }
  32388. if ( fromTypeLength > toTypeLength ) {
  32389. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  32390. }
  32391. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  32392. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  32393. }
  32394. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  32395. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  32396. }
  32397. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  32398. // convert a number value to vector type, e.g:
  32399. // vec3( 1u ) -> vec3( float( 1u ) )
  32400. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  32401. }
  32402. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  32403. }
  32404. /**
  32405. * Returns a signature with the engine's current revision.
  32406. *
  32407. * @return {string} The signature.
  32408. */
  32409. getSignature() {
  32410. return `// Three.js r${ REVISION } - Node System\n`;
  32411. }
  32412. // Deprecated
  32413. /**
  32414. * @function
  32415. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  32416. *
  32417. * @param {string} [type='NodeMaterial'] - The node material type.
  32418. * @throws {Error}
  32419. */
  32420. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  32421. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  32422. }
  32423. }
  32424. /**
  32425. * Management class for updating nodes. The module tracks metrics like
  32426. * the elapsed time, delta time, the render and frame ID to correctly
  32427. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  32428. * and {@link Node#updateAfter} depending on the node's configuration.
  32429. */
  32430. class NodeFrame {
  32431. /**
  32432. * Constructs a new node fame.
  32433. */
  32434. constructor() {
  32435. /**
  32436. * The elapsed time in seconds.
  32437. *
  32438. * @type {number}
  32439. * @default 0
  32440. */
  32441. this.time = 0;
  32442. /**
  32443. * The delta time in seconds.
  32444. *
  32445. * @type {number}
  32446. * @default 0
  32447. */
  32448. this.deltaTime = 0;
  32449. /**
  32450. * The frame ID.
  32451. *
  32452. * @type {number}
  32453. * @default 0
  32454. */
  32455. this.frameId = 0;
  32456. /**
  32457. * The render ID.
  32458. *
  32459. * @type {number}
  32460. * @default 0
  32461. */
  32462. this.renderId = 0;
  32463. /**
  32464. * Used to control the {@link Node#update} call.
  32465. *
  32466. * @type {WeakMap<Node, Object>}
  32467. */
  32468. this.updateMap = new WeakMap();
  32469. /**
  32470. * Used to control the {@link Node#updateBefore} call.
  32471. *
  32472. * @type {WeakMap<Node, Object>}
  32473. */
  32474. this.updateBeforeMap = new WeakMap();
  32475. /**
  32476. * Used to control the {@link Node#updateAfter} call.
  32477. *
  32478. * @type {WeakMap<Node, Object>}
  32479. */
  32480. this.updateAfterMap = new WeakMap();
  32481. /**
  32482. * A reference to the current renderer.
  32483. *
  32484. * @type {?Renderer}
  32485. * @default null
  32486. */
  32487. this.renderer = null;
  32488. /**
  32489. * A reference to the current material.
  32490. *
  32491. * @type {?Material}
  32492. * @default null
  32493. */
  32494. this.material = null;
  32495. /**
  32496. * A reference to the current camera.
  32497. *
  32498. * @type {?Camera}
  32499. * @default null
  32500. */
  32501. this.camera = null;
  32502. /**
  32503. * A reference to the current 3D object.
  32504. *
  32505. * @type {?Object3D}
  32506. * @default null
  32507. */
  32508. this.object = null;
  32509. /**
  32510. * A reference to the current scene.
  32511. *
  32512. * @type {?Scene}
  32513. * @default null
  32514. */
  32515. this.scene = null;
  32516. }
  32517. /**
  32518. * Returns a dictionary for a given node and update map which
  32519. * is used to correctly call node update methods per frame or render.
  32520. *
  32521. * @private
  32522. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  32523. * @param {Node} nodeRef - The reference to the current node.
  32524. * @return {Object<string,WeakMap>} The dictionary.
  32525. */
  32526. _getMaps( referenceMap, nodeRef ) {
  32527. let maps = referenceMap.get( nodeRef );
  32528. if ( maps === undefined ) {
  32529. maps = {
  32530. renderMap: new WeakMap(),
  32531. frameMap: new WeakMap()
  32532. };
  32533. referenceMap.set( nodeRef, maps );
  32534. }
  32535. return maps;
  32536. }
  32537. /**
  32538. * This method executes the {@link Node#updateBefore} for the given node.
  32539. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  32540. * is only executed once per frame, render or object depending on the update
  32541. * type.
  32542. *
  32543. * @param {Node} node - The node that should be updated.
  32544. */
  32545. updateBeforeNode( node ) {
  32546. const updateType = node.getUpdateBeforeType();
  32547. const reference = node.updateReference( this );
  32548. if ( updateType === NodeUpdateType.FRAME ) {
  32549. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  32550. if ( frameMap.get( reference ) !== this.frameId ) {
  32551. if ( node.updateBefore( this ) !== false ) {
  32552. frameMap.set( reference, this.frameId );
  32553. }
  32554. }
  32555. } else if ( updateType === NodeUpdateType.RENDER ) {
  32556. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  32557. if ( renderMap.get( reference ) !== this.renderId ) {
  32558. if ( node.updateBefore( this ) !== false ) {
  32559. renderMap.set( reference, this.renderId );
  32560. }
  32561. }
  32562. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32563. node.updateBefore( this );
  32564. }
  32565. }
  32566. /**
  32567. * This method executes the {@link Node#updateAfter} for the given node.
  32568. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  32569. * is only executed once per frame, render or object depending on the update
  32570. * type.
  32571. *
  32572. * @param {Node} node - The node that should be updated.
  32573. */
  32574. updateAfterNode( node ) {
  32575. const updateType = node.getUpdateAfterType();
  32576. const reference = node.updateReference( this );
  32577. if ( updateType === NodeUpdateType.FRAME ) {
  32578. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  32579. if ( frameMap.get( reference ) !== this.frameId ) {
  32580. if ( node.updateAfter( this ) !== false ) {
  32581. frameMap.set( reference, this.frameId );
  32582. }
  32583. }
  32584. } else if ( updateType === NodeUpdateType.RENDER ) {
  32585. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  32586. if ( renderMap.get( reference ) !== this.renderId ) {
  32587. if ( node.updateAfter( this ) !== false ) {
  32588. renderMap.set( reference, this.renderId );
  32589. }
  32590. }
  32591. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32592. node.updateAfter( this );
  32593. }
  32594. }
  32595. /**
  32596. * This method executes the {@link Node#update} for the given node.
  32597. * It makes sure {@link Node#updateType} is honored meaning the update
  32598. * is only executed once per frame, render or object depending on the update
  32599. * type.
  32600. *
  32601. * @param {Node} node - The node that should be updated.
  32602. */
  32603. updateNode( node ) {
  32604. const updateType = node.getUpdateType();
  32605. const reference = node.updateReference( this );
  32606. if ( updateType === NodeUpdateType.FRAME ) {
  32607. const { frameMap } = this._getMaps( this.updateMap, reference );
  32608. if ( frameMap.get( reference ) !== this.frameId ) {
  32609. if ( node.update( this ) !== false ) {
  32610. frameMap.set( reference, this.frameId );
  32611. }
  32612. }
  32613. } else if ( updateType === NodeUpdateType.RENDER ) {
  32614. const { renderMap } = this._getMaps( this.updateMap, reference );
  32615. if ( renderMap.get( reference ) !== this.renderId ) {
  32616. if ( node.update( this ) !== false ) {
  32617. renderMap.set( reference, this.renderId );
  32618. }
  32619. }
  32620. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32621. node.update( this );
  32622. }
  32623. }
  32624. /**
  32625. * Updates the internal state of the node frame. This method is
  32626. * called by the renderer in its internal animation loop.
  32627. */
  32628. update() {
  32629. this.frameId ++;
  32630. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  32631. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  32632. this.lastTime = performance.now();
  32633. this.time += this.deltaTime;
  32634. }
  32635. }
  32636. /**
  32637. * Describes the input of a {@link NodeFunction}.
  32638. */
  32639. class NodeFunctionInput {
  32640. /**
  32641. * Constructs a new node function input.
  32642. *
  32643. * @param {string} type - The input type.
  32644. * @param {string} name - The input name.
  32645. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  32646. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  32647. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  32648. */
  32649. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  32650. /**
  32651. * The input type.
  32652. *
  32653. * @type {string}
  32654. */
  32655. this.type = type;
  32656. /**
  32657. * The input name.
  32658. *
  32659. * @type {string}
  32660. */
  32661. this.name = name;
  32662. /**
  32663. * If the input is an Array, count will be the length.
  32664. *
  32665. * @type {?number}
  32666. * @default null
  32667. */
  32668. this.count = count;
  32669. /**
  32670. *The parameter qualifier (only relevant for GLSL).
  32671. *
  32672. * @type {('in'|'out'|'inout')}
  32673. * @default ''
  32674. */
  32675. this.qualifier = qualifier;
  32676. /**
  32677. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  32678. *
  32679. * @type {boolean}
  32680. * @default false
  32681. */
  32682. this.isConst = isConst;
  32683. }
  32684. }
  32685. NodeFunctionInput.isNodeFunctionInput = true;
  32686. /**
  32687. * Module for representing directional lights as nodes.
  32688. *
  32689. * @augments AnalyticLightNode
  32690. */
  32691. class DirectionalLightNode extends AnalyticLightNode {
  32692. static get type() {
  32693. return 'DirectionalLightNode';
  32694. }
  32695. /**
  32696. * Constructs a new directional light node.
  32697. *
  32698. * @param {?DirectionalLight} [light=null] - The directional light source.
  32699. */
  32700. constructor( light = null ) {
  32701. super( light );
  32702. }
  32703. setupDirect() {
  32704. const lightColor = this.colorNode;
  32705. const lightDirection = lightTargetDirection( this.light );
  32706. return { lightDirection, lightColor };
  32707. }
  32708. }
  32709. const _matrix41 = /*@__PURE__*/ new Matrix4();
  32710. const _matrix42 = /*@__PURE__*/ new Matrix4();
  32711. let _ltcLib = null;
  32712. /**
  32713. * Module for representing rect area lights as nodes.
  32714. *
  32715. * @augments AnalyticLightNode
  32716. */
  32717. class RectAreaLightNode extends AnalyticLightNode {
  32718. static get type() {
  32719. return 'RectAreaLightNode';
  32720. }
  32721. /**
  32722. * Constructs a new rect area light node.
  32723. *
  32724. * @param {?RectAreaLight} [light=null] - The rect area light source.
  32725. */
  32726. constructor( light = null ) {
  32727. super( light );
  32728. /**
  32729. * Uniform node representing the half height of the are light.
  32730. *
  32731. * @type {UniformNode<vec3>}
  32732. */
  32733. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  32734. /**
  32735. * Uniform node representing the half width of the are light.
  32736. *
  32737. * @type {UniformNode<vec3>}
  32738. */
  32739. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  32740. /**
  32741. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  32742. * relies on `viewMatrix` which might vary per render call.
  32743. *
  32744. * @type {string}
  32745. * @default 'render'
  32746. */
  32747. this.updateType = NodeUpdateType.RENDER;
  32748. }
  32749. /**
  32750. * Overwritten to updated rect area light specific uniforms.
  32751. *
  32752. * @param {NodeFrame} frame - A reference to the current node frame.
  32753. */
  32754. update( frame ) {
  32755. super.update( frame );
  32756. const { light } = this;
  32757. const viewMatrix = frame.camera.matrixWorldInverse;
  32758. _matrix42.identity();
  32759. _matrix41.copy( light.matrixWorld );
  32760. _matrix41.premultiply( viewMatrix );
  32761. _matrix42.extractRotation( _matrix41 );
  32762. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  32763. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  32764. this.halfWidth.value.applyMatrix4( _matrix42 );
  32765. this.halfHeight.value.applyMatrix4( _matrix42 );
  32766. }
  32767. setupDirectRectArea( builder ) {
  32768. let ltc_1, ltc_2;
  32769. if ( builder.isAvailable( 'float32Filterable' ) ) {
  32770. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  32771. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  32772. } else {
  32773. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  32774. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  32775. }
  32776. const { colorNode, light } = this;
  32777. const lightPosition = lightViewPosition( light );
  32778. return {
  32779. lightColor: colorNode,
  32780. lightPosition,
  32781. halfWidth: this.halfWidth,
  32782. halfHeight: this.halfHeight,
  32783. ltc_1,
  32784. ltc_2
  32785. };
  32786. }
  32787. /**
  32788. * Used to configure the internal BRDF approximation texture data.
  32789. *
  32790. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  32791. */
  32792. static setLTC( ltc ) {
  32793. _ltcLib = ltc;
  32794. }
  32795. }
  32796. /**
  32797. * Module for representing spot lights as nodes.
  32798. *
  32799. * @augments AnalyticLightNode
  32800. */
  32801. class SpotLightNode extends AnalyticLightNode {
  32802. static get type() {
  32803. return 'SpotLightNode';
  32804. }
  32805. /**
  32806. * Constructs a new spot light node.
  32807. *
  32808. * @param {?SpotLight} [light=null] - The spot light source.
  32809. */
  32810. constructor( light = null ) {
  32811. super( light );
  32812. /**
  32813. * Uniform node representing the cone cosine.
  32814. *
  32815. * @type {UniformNode<float>}
  32816. */
  32817. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  32818. /**
  32819. * Uniform node representing the penumbra cosine.
  32820. *
  32821. * @type {UniformNode<float>}
  32822. */
  32823. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  32824. /**
  32825. * Uniform node representing the cutoff distance.
  32826. *
  32827. * @type {UniformNode<float>}
  32828. */
  32829. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  32830. /**
  32831. * Uniform node representing the decay exponent.
  32832. *
  32833. * @type {UniformNode<float>}
  32834. */
  32835. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  32836. }
  32837. /**
  32838. * Overwritten to updated spot light specific uniforms.
  32839. *
  32840. * @param {NodeFrame} frame - A reference to the current node frame.
  32841. */
  32842. update( frame ) {
  32843. super.update( frame );
  32844. const { light } = this;
  32845. this.coneCosNode.value = Math.cos( light.angle );
  32846. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  32847. this.cutoffDistanceNode.value = light.distance;
  32848. this.decayExponentNode.value = light.decay;
  32849. }
  32850. /**
  32851. * Computes the spot attenuation for the given angle.
  32852. *
  32853. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32854. * @return {Node<float>} The spot attenuation.
  32855. */
  32856. getSpotAttenuation( angleCosine ) {
  32857. const { coneCosNode, penumbraCosNode } = this;
  32858. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  32859. }
  32860. setupDirect( builder ) {
  32861. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  32862. const lightVector = this.getLightVector( builder );
  32863. const lightDirection = lightVector.normalize();
  32864. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  32865. const spotAttenuation = this.getSpotAttenuation( angleCos );
  32866. const lightDistance = lightVector.length();
  32867. const lightAttenuation = getDistanceAttenuation( {
  32868. lightDistance,
  32869. cutoffDistance: cutoffDistanceNode,
  32870. decayExponent: decayExponentNode
  32871. } );
  32872. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  32873. if ( light.map ) {
  32874. const spotLightCoord = lightProjectionUV( light, builder.context.positionWorld );
  32875. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  32876. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  32877. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  32878. }
  32879. return { lightColor, lightDirection };
  32880. }
  32881. }
  32882. /**
  32883. * An IES version of the default spot light node.
  32884. *
  32885. * @augments SpotLightNode
  32886. */
  32887. class IESSpotLightNode extends SpotLightNode {
  32888. static get type() {
  32889. return 'IESSpotLightNode';
  32890. }
  32891. /**
  32892. * Overwrites the default implementation to compute an IES conform spot attenuation.
  32893. *
  32894. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  32895. * @return {Node<float>} The spot attenuation.
  32896. */
  32897. getSpotAttenuation( angleCosine ) {
  32898. const iesMap = this.light.iesMap;
  32899. let spotAttenuation = null;
  32900. if ( iesMap && iesMap.isTexture === true ) {
  32901. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  32902. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  32903. } else {
  32904. spotAttenuation = super.getSpotAttenuation( angleCosine );
  32905. }
  32906. return spotAttenuation;
  32907. }
  32908. }
  32909. /**
  32910. * Module for representing ambient lights as nodes.
  32911. *
  32912. * @augments AnalyticLightNode
  32913. */
  32914. class AmbientLightNode extends AnalyticLightNode {
  32915. static get type() {
  32916. return 'AmbientLightNode';
  32917. }
  32918. /**
  32919. * Constructs a new ambient light node.
  32920. *
  32921. * @param {?AmbientLight} [light=null] - The ambient light source.
  32922. */
  32923. constructor( light = null ) {
  32924. super( light );
  32925. }
  32926. setup( { context } ) {
  32927. context.irradiance.addAssign( this.colorNode );
  32928. }
  32929. }
  32930. /**
  32931. * Module for representing hemisphere lights as nodes.
  32932. *
  32933. * @augments AnalyticLightNode
  32934. */
  32935. class HemisphereLightNode extends AnalyticLightNode {
  32936. static get type() {
  32937. return 'HemisphereLightNode';
  32938. }
  32939. /**
  32940. * Constructs a new hemisphere light node.
  32941. *
  32942. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  32943. */
  32944. constructor( light = null ) {
  32945. super( light );
  32946. /**
  32947. * Uniform node representing the light's position.
  32948. *
  32949. * @type {UniformNode<vec3>}
  32950. */
  32951. this.lightPositionNode = lightPosition( light );
  32952. /**
  32953. * A node representing the light's direction.
  32954. *
  32955. * @type {Node<vec3>}
  32956. */
  32957. this.lightDirectionNode = this.lightPositionNode.normalize();
  32958. /**
  32959. * Uniform node representing the light's ground color.
  32960. *
  32961. * @type {UniformNode<vec3>}
  32962. */
  32963. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  32964. }
  32965. /**
  32966. * Overwritten to updated hemisphere light specific uniforms.
  32967. *
  32968. * @param {NodeFrame} frame - A reference to the current node frame.
  32969. */
  32970. update( frame ) {
  32971. const { light } = this;
  32972. super.update( frame );
  32973. this.lightPositionNode.object3d = light;
  32974. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  32975. }
  32976. setup( builder ) {
  32977. const { colorNode, groundColorNode, lightDirectionNode } = this;
  32978. const dotNL = normalView.dot( lightDirectionNode );
  32979. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  32980. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  32981. builder.context.irradiance.addAssign( irradiance );
  32982. }
  32983. }
  32984. /**
  32985. * Module for representing light probes as nodes.
  32986. *
  32987. * @augments AnalyticLightNode
  32988. */
  32989. class LightProbeNode extends AnalyticLightNode {
  32990. static get type() {
  32991. return 'LightProbeNode';
  32992. }
  32993. /**
  32994. * Constructs a new light probe node.
  32995. *
  32996. * @param {?LightProbe} [light=null] - The light probe.
  32997. */
  32998. constructor( light = null ) {
  32999. super( light );
  33000. const array = [];
  33001. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  33002. /**
  33003. * Light probe represented as a uniform of spherical harmonics.
  33004. *
  33005. * @type {UniformArrayNode}
  33006. */
  33007. this.lightProbe = uniformArray( array );
  33008. }
  33009. /**
  33010. * Overwritten to updated light probe specific uniforms.
  33011. *
  33012. * @param {NodeFrame} frame - A reference to the current node frame.
  33013. */
  33014. update( frame ) {
  33015. const { light } = this;
  33016. super.update( frame );
  33017. //
  33018. for ( let i = 0; i < 9; i ++ ) {
  33019. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  33020. }
  33021. }
  33022. setup( builder ) {
  33023. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  33024. builder.context.irradiance.addAssign( irradiance );
  33025. }
  33026. }
  33027. /**
  33028. * Base class for node parsers. A derived parser must be implemented
  33029. * for each supported native shader language.
  33030. */
  33031. class NodeParser {
  33032. /**
  33033. * The method parses the given native code an returns a node function.
  33034. *
  33035. * @abstract
  33036. * @param {string} source - The native shader code.
  33037. * @return {NodeFunction} A node function.
  33038. */
  33039. parseFunction( /*source*/ ) {
  33040. console.warn( 'Abstract function.' );
  33041. }
  33042. }
  33043. /**
  33044. * Base class for node functions. A derived module must be implemented
  33045. * for each supported native shader language. Similar to other `Node*` modules,
  33046. * this class is only relevant during the building process and not used
  33047. * in user-level code.
  33048. */
  33049. class NodeFunction {
  33050. /**
  33051. * Constructs a new node function.
  33052. *
  33053. * @param {string} type - The node type. This type is the return type of the node function.
  33054. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  33055. * @param {string} [name=''] - The function's name.
  33056. * @param {string} [precision=''] - The precision qualifier.
  33057. */
  33058. constructor( type, inputs, name = '', precision = '' ) {
  33059. /**
  33060. * The node type. This type is the return type of the node function.
  33061. *
  33062. * @type {string}
  33063. */
  33064. this.type = type;
  33065. /**
  33066. * The function's inputs.
  33067. *
  33068. * @type {Array<NodeFunctionInput>}
  33069. */
  33070. this.inputs = inputs;
  33071. /**
  33072. * The name of the uniform.
  33073. *
  33074. * @type {string}
  33075. * @default ''
  33076. */
  33077. this.name = name;
  33078. /**
  33079. * The precision qualifier.
  33080. *
  33081. * @type {string}
  33082. * @default ''
  33083. */
  33084. this.precision = precision;
  33085. }
  33086. /**
  33087. * This method returns the native code of the node function.
  33088. *
  33089. * @abstract
  33090. * @param {string} name - The function's name.
  33091. * @return {string} A shader code.
  33092. */
  33093. getCode( /*name = this.name*/ ) {
  33094. console.warn( 'Abstract function.' );
  33095. }
  33096. }
  33097. NodeFunction.isNodeFunction = true;
  33098. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  33099. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  33100. const pragmaMain = '#pragma main';
  33101. const parse$1 = ( source ) => {
  33102. source = source.trim();
  33103. const pragmaMainIndex = source.indexOf( pragmaMain );
  33104. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  33105. const declaration = mainCode.match( declarationRegexp$1 );
  33106. if ( declaration !== null && declaration.length === 5 ) {
  33107. // tokenizer
  33108. const inputsCode = declaration[ 4 ];
  33109. const propsMatches = [];
  33110. let nameMatch = null;
  33111. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  33112. propsMatches.push( nameMatch );
  33113. }
  33114. // parser
  33115. const inputs = [];
  33116. let i = 0;
  33117. while ( i < propsMatches.length ) {
  33118. const isConst = propsMatches[ i ][ 0 ] === 'const';
  33119. if ( isConst === true ) {
  33120. i ++;
  33121. }
  33122. let qualifier = propsMatches[ i ][ 0 ];
  33123. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  33124. i ++;
  33125. } else {
  33126. qualifier = '';
  33127. }
  33128. const type = propsMatches[ i ++ ][ 0 ];
  33129. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  33130. if ( Number.isNaN( count ) === false ) i ++;
  33131. else count = null;
  33132. const name = propsMatches[ i ++ ][ 0 ];
  33133. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  33134. }
  33135. //
  33136. const blockCode = mainCode.substring( declaration[ 0 ].length );
  33137. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  33138. const type = declaration[ 2 ];
  33139. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  33140. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  33141. return {
  33142. type,
  33143. inputs,
  33144. name,
  33145. precision,
  33146. inputsCode,
  33147. blockCode,
  33148. headerCode
  33149. };
  33150. } else {
  33151. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  33152. }
  33153. };
  33154. /**
  33155. * This class represents a GLSL node function.
  33156. *
  33157. * @augments NodeFunction
  33158. */
  33159. class GLSLNodeFunction extends NodeFunction {
  33160. /**
  33161. * Constructs a new GLSL node function.
  33162. *
  33163. * @param {string} source - The GLSL source.
  33164. */
  33165. constructor( source ) {
  33166. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  33167. super( type, inputs, name, precision );
  33168. this.inputsCode = inputsCode;
  33169. this.blockCode = blockCode;
  33170. this.headerCode = headerCode;
  33171. }
  33172. /**
  33173. * This method returns the GLSL code of the node function.
  33174. *
  33175. * @param {string} [name=this.name] - The function's name.
  33176. * @return {string} The shader code.
  33177. */
  33178. getCode( name = this.name ) {
  33179. let code;
  33180. const blockCode = this.blockCode;
  33181. if ( blockCode !== '' ) {
  33182. const { type, inputsCode, headerCode, precision } = this;
  33183. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  33184. if ( precision !== '' ) {
  33185. declarationCode = `${ precision } ${ declarationCode }`;
  33186. }
  33187. code = headerCode + declarationCode + blockCode;
  33188. } else {
  33189. // interface function
  33190. code = '';
  33191. }
  33192. return code;
  33193. }
  33194. }
  33195. /**
  33196. * A GLSL node parser.
  33197. *
  33198. * @augments NodeParser
  33199. */
  33200. class GLSLNodeParser extends NodeParser {
  33201. /**
  33202. * The method parses the given GLSL code an returns a node function.
  33203. *
  33204. * @param {string} source - The GLSL code.
  33205. * @return {GLSLNodeFunction} A node function.
  33206. */
  33207. parseFunction( source ) {
  33208. return new GLSLNodeFunction( source );
  33209. }
  33210. }
  33211. const _outputNodeMap = new WeakMap();
  33212. const _chainKeys$2 = [];
  33213. const _cacheKeyValues = [];
  33214. /**
  33215. * This renderer module manages node-related objects and is the
  33216. * primary interface between the renderer and the node system.
  33217. *
  33218. * @private
  33219. * @augments DataMap
  33220. */
  33221. class Nodes extends DataMap {
  33222. /**
  33223. * Constructs a new nodes management component.
  33224. *
  33225. * @param {Renderer} renderer - The renderer.
  33226. * @param {Backend} backend - The renderer's backend.
  33227. */
  33228. constructor( renderer, backend ) {
  33229. super();
  33230. /**
  33231. * The renderer.
  33232. *
  33233. * @type {Renderer}
  33234. */
  33235. this.renderer = renderer;
  33236. /**
  33237. * The renderer's backend.
  33238. *
  33239. * @type {Backend}
  33240. */
  33241. this.backend = backend;
  33242. /**
  33243. * The node frame.
  33244. *
  33245. * @type {Renderer}
  33246. */
  33247. this.nodeFrame = new NodeFrame();
  33248. /**
  33249. * A cache for managing node builder states.
  33250. *
  33251. * @type {Map<number,NodeBuilderState>}
  33252. */
  33253. this.nodeBuilderCache = new Map();
  33254. /**
  33255. * A cache for managing data cache key data.
  33256. *
  33257. * @type {ChainMap}
  33258. */
  33259. this.callHashCache = new ChainMap();
  33260. /**
  33261. * A cache for managing node uniforms group data.
  33262. *
  33263. * @type {ChainMap}
  33264. */
  33265. this.groupsData = new ChainMap();
  33266. /**
  33267. * A cache for managing node objects of
  33268. * scene properties like fog or environments.
  33269. *
  33270. * @type {Object<string,WeakMap>}
  33271. */
  33272. this.cacheLib = {};
  33273. }
  33274. /**
  33275. * Returns `true` if the given node uniforms group must be updated or not.
  33276. *
  33277. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  33278. * @return {boolean} Whether the node uniforms group requires an update or not.
  33279. */
  33280. updateGroup( nodeUniformsGroup ) {
  33281. const groupNode = nodeUniformsGroup.groupNode;
  33282. const name = groupNode.name;
  33283. // objectGroup is always updated
  33284. if ( name === objectGroup.name ) return true;
  33285. // renderGroup is updated once per render/compute call
  33286. if ( name === renderGroup.name ) {
  33287. const uniformsGroupData = this.get( nodeUniformsGroup );
  33288. const renderId = this.nodeFrame.renderId;
  33289. if ( uniformsGroupData.renderId !== renderId ) {
  33290. uniformsGroupData.renderId = renderId;
  33291. return true;
  33292. }
  33293. return false;
  33294. }
  33295. // frameGroup is updated once per frame
  33296. if ( name === frameGroup.name ) {
  33297. const uniformsGroupData = this.get( nodeUniformsGroup );
  33298. const frameId = this.nodeFrame.frameId;
  33299. if ( uniformsGroupData.frameId !== frameId ) {
  33300. uniformsGroupData.frameId = frameId;
  33301. return true;
  33302. }
  33303. return false;
  33304. }
  33305. // other groups are updated just when groupNode.needsUpdate is true
  33306. _chainKeys$2[ 0 ] = groupNode;
  33307. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  33308. let groupData = this.groupsData.get( _chainKeys$2 );
  33309. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  33310. _chainKeys$2.length = 0;
  33311. if ( groupData.version !== groupNode.version ) {
  33312. groupData.version = groupNode.version;
  33313. return true;
  33314. }
  33315. return false;
  33316. }
  33317. /**
  33318. * Returns the cache key for the given render object.
  33319. *
  33320. * @param {RenderObject} renderObject - The render object.
  33321. * @return {number} The cache key.
  33322. */
  33323. getForRenderCacheKey( renderObject ) {
  33324. return renderObject.initialCacheKey;
  33325. }
  33326. /**
  33327. * Returns a node builder state for the given render object.
  33328. *
  33329. * @param {RenderObject} renderObject - The render object.
  33330. * @return {NodeBuilderState} The node builder state.
  33331. */
  33332. getForRender( renderObject ) {
  33333. const renderObjectData = this.get( renderObject );
  33334. let nodeBuilderState = renderObjectData.nodeBuilderState;
  33335. if ( nodeBuilderState === undefined ) {
  33336. const { nodeBuilderCache } = this;
  33337. const cacheKey = this.getForRenderCacheKey( renderObject );
  33338. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  33339. if ( nodeBuilderState === undefined ) {
  33340. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  33341. nodeBuilder.scene = renderObject.scene;
  33342. nodeBuilder.material = renderObject.material;
  33343. nodeBuilder.camera = renderObject.camera;
  33344. nodeBuilder.context.material = renderObject.material;
  33345. nodeBuilder.lightsNode = renderObject.lightsNode;
  33346. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  33347. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  33348. nodeBuilder.clippingContext = renderObject.clippingContext;
  33349. nodeBuilder.build();
  33350. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  33351. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  33352. }
  33353. nodeBuilderState.usedTimes ++;
  33354. renderObjectData.nodeBuilderState = nodeBuilderState;
  33355. }
  33356. return nodeBuilderState;
  33357. }
  33358. /**
  33359. * Deletes the given object from the internal data map
  33360. *
  33361. * @param {any} object - The object to delete.
  33362. * @return {?Object} The deleted dictionary.
  33363. */
  33364. delete( object ) {
  33365. if ( object.isRenderObject ) {
  33366. const nodeBuilderState = this.get( object ).nodeBuilderState;
  33367. nodeBuilderState.usedTimes --;
  33368. if ( nodeBuilderState.usedTimes === 0 ) {
  33369. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  33370. }
  33371. }
  33372. return super.delete( object );
  33373. }
  33374. /**
  33375. * Returns a node builder state for the given compute node.
  33376. *
  33377. * @param {Node} computeNode - The compute node.
  33378. * @return {NodeBuilderState} The node builder state.
  33379. */
  33380. getForCompute( computeNode ) {
  33381. const computeData = this.get( computeNode );
  33382. let nodeBuilderState = computeData.nodeBuilderState;
  33383. if ( nodeBuilderState === undefined ) {
  33384. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  33385. nodeBuilder.build();
  33386. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  33387. computeData.nodeBuilderState = nodeBuilderState;
  33388. }
  33389. return nodeBuilderState;
  33390. }
  33391. /**
  33392. * Creates a node builder state for the given node builder.
  33393. *
  33394. * @private
  33395. * @param {NodeBuilder} nodeBuilder - The node builder.
  33396. * @return {NodeBuilderState} The node builder state.
  33397. */
  33398. _createNodeBuilderState( nodeBuilder ) {
  33399. return new NodeBuilderState(
  33400. nodeBuilder.vertexShader,
  33401. nodeBuilder.fragmentShader,
  33402. nodeBuilder.computeShader,
  33403. nodeBuilder.getAttributesArray(),
  33404. nodeBuilder.getBindings(),
  33405. nodeBuilder.updateNodes,
  33406. nodeBuilder.updateBeforeNodes,
  33407. nodeBuilder.updateAfterNodes,
  33408. nodeBuilder.observer,
  33409. nodeBuilder.transforms
  33410. );
  33411. }
  33412. /**
  33413. * Returns an environment node for the current configured
  33414. * scene environment.
  33415. *
  33416. * @param {Scene} scene - The scene.
  33417. * @return {Node} A node representing the current scene environment.
  33418. */
  33419. getEnvironmentNode( scene ) {
  33420. this.updateEnvironment( scene );
  33421. let environmentNode = null;
  33422. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  33423. environmentNode = scene.environmentNode;
  33424. } else {
  33425. const sceneData = this.get( scene );
  33426. if ( sceneData.environmentNode ) {
  33427. environmentNode = sceneData.environmentNode;
  33428. }
  33429. }
  33430. return environmentNode;
  33431. }
  33432. /**
  33433. * Returns a background node for the current configured
  33434. * scene background.
  33435. *
  33436. * @param {Scene} scene - The scene.
  33437. * @return {Node} A node representing the current scene background.
  33438. */
  33439. getBackgroundNode( scene ) {
  33440. this.updateBackground( scene );
  33441. let backgroundNode = null;
  33442. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  33443. backgroundNode = scene.backgroundNode;
  33444. } else {
  33445. const sceneData = this.get( scene );
  33446. if ( sceneData.backgroundNode ) {
  33447. backgroundNode = sceneData.backgroundNode;
  33448. }
  33449. }
  33450. return backgroundNode;
  33451. }
  33452. /**
  33453. * Returns a fog node for the current configured scene fog.
  33454. *
  33455. * @param {Scene} scene - The scene.
  33456. * @return {Node} A node representing the current scene fog.
  33457. */
  33458. getFogNode( scene ) {
  33459. this.updateFog( scene );
  33460. return scene.fogNode || this.get( scene ).fogNode || null;
  33461. }
  33462. /**
  33463. * Returns a cache key for the given scene and lights node.
  33464. * This key is used by `RenderObject` as a part of the dynamic
  33465. * cache key (a key that must be checked every time the render
  33466. * objects is drawn).
  33467. *
  33468. * @param {Scene} scene - The scene.
  33469. * @param {LightsNode} lightsNode - The lights node.
  33470. * @return {number} The cache key.
  33471. */
  33472. getCacheKey( scene, lightsNode ) {
  33473. _chainKeys$2[ 0 ] = scene;
  33474. _chainKeys$2[ 1 ] = lightsNode;
  33475. const callId = this.renderer.info.calls;
  33476. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  33477. if ( cacheKeyData.callId !== callId ) {
  33478. const environmentNode = this.getEnvironmentNode( scene );
  33479. const fogNode = this.getFogNode( scene );
  33480. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  33481. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  33482. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  33483. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  33484. cacheKeyData.callId = callId;
  33485. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  33486. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  33487. _cacheKeyValues.length = 0;
  33488. }
  33489. _chainKeys$2.length = 0;
  33490. return cacheKeyData.cacheKey;
  33491. }
  33492. /**
  33493. * A boolean that indicates whether tone mapping should be enabled
  33494. * or not.
  33495. *
  33496. * @type {boolean}
  33497. */
  33498. get isToneMappingState() {
  33499. return this.renderer.getRenderTarget() ? false : true;
  33500. }
  33501. /**
  33502. * If a scene background is configured, this method makes sure to
  33503. * represent the background with a corresponding node-based implementation.
  33504. *
  33505. * @param {Scene} scene - The scene.
  33506. */
  33507. updateBackground( scene ) {
  33508. const sceneData = this.get( scene );
  33509. const background = scene.background;
  33510. if ( background ) {
  33511. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  33512. if ( sceneData.background !== background || forceUpdate ) {
  33513. const backgroundNode = this.getCacheNode( 'background', background, () => {
  33514. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  33515. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  33516. return pmremTexture( background );
  33517. } else {
  33518. let envMap;
  33519. if ( background.isCubeTexture === true ) {
  33520. envMap = cubeTexture( background );
  33521. } else {
  33522. envMap = texture( background );
  33523. }
  33524. return cubeMapNode( envMap );
  33525. }
  33526. } else if ( background.isTexture === true ) {
  33527. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  33528. } else if ( background.isColor !== true ) {
  33529. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  33530. }
  33531. }, forceUpdate );
  33532. sceneData.backgroundNode = backgroundNode;
  33533. sceneData.background = background;
  33534. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  33535. }
  33536. } else if ( sceneData.backgroundNode ) {
  33537. delete sceneData.backgroundNode;
  33538. delete sceneData.background;
  33539. }
  33540. }
  33541. /**
  33542. * This method is part of the caching of nodes which are used to represents the
  33543. * scene's background, fog or environment.
  33544. *
  33545. * @param {string} type - The type of object to cache.
  33546. * @param {Object} object - The object.
  33547. * @param {Function} callback - A callback that produces a node representation for the given object.
  33548. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  33549. * @return {Node} The node representation.
  33550. */
  33551. getCacheNode( type, object, callback, forceUpdate = false ) {
  33552. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  33553. let node = nodeCache.get( object );
  33554. if ( node === undefined || forceUpdate ) {
  33555. node = callback();
  33556. nodeCache.set( object, node );
  33557. }
  33558. return node;
  33559. }
  33560. /**
  33561. * If a scene fog is configured, this method makes sure to
  33562. * represent the fog with a corresponding node-based implementation.
  33563. *
  33564. * @param {Scene} scene - The scene.
  33565. */
  33566. updateFog( scene ) {
  33567. const sceneData = this.get( scene );
  33568. const sceneFog = scene.fog;
  33569. if ( sceneFog ) {
  33570. if ( sceneData.fog !== sceneFog ) {
  33571. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  33572. if ( sceneFog.isFogExp2 ) {
  33573. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  33574. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  33575. return fog( color, densityFogFactor( density ) );
  33576. } else if ( sceneFog.isFog ) {
  33577. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  33578. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  33579. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  33580. return fog( color, rangeFogFactor( near, far ) );
  33581. } else {
  33582. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  33583. }
  33584. } );
  33585. sceneData.fogNode = fogNode;
  33586. sceneData.fog = sceneFog;
  33587. }
  33588. } else {
  33589. delete sceneData.fogNode;
  33590. delete sceneData.fog;
  33591. }
  33592. }
  33593. /**
  33594. * If a scene environment is configured, this method makes sure to
  33595. * represent the environment with a corresponding node-based implementation.
  33596. *
  33597. * @param {Scene} scene - The scene.
  33598. */
  33599. updateEnvironment( scene ) {
  33600. const sceneData = this.get( scene );
  33601. const environment = scene.environment;
  33602. if ( environment ) {
  33603. if ( sceneData.environment !== environment ) {
  33604. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  33605. if ( environment.isCubeTexture === true ) {
  33606. return cubeTexture( environment );
  33607. } else if ( environment.isTexture === true ) {
  33608. return texture( environment );
  33609. } else {
  33610. console.error( 'Nodes: Unsupported environment configuration.', environment );
  33611. }
  33612. } );
  33613. sceneData.environmentNode = environmentNode;
  33614. sceneData.environment = environment;
  33615. }
  33616. } else if ( sceneData.environmentNode ) {
  33617. delete sceneData.environmentNode;
  33618. delete sceneData.environment;
  33619. }
  33620. }
  33621. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  33622. const nodeFrame = this.nodeFrame;
  33623. nodeFrame.renderer = renderer;
  33624. nodeFrame.scene = scene;
  33625. nodeFrame.object = object;
  33626. nodeFrame.camera = camera;
  33627. nodeFrame.material = material;
  33628. return nodeFrame;
  33629. }
  33630. getNodeFrameForRender( renderObject ) {
  33631. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  33632. }
  33633. /**
  33634. * Returns the current output cache key.
  33635. *
  33636. * @return {string} The output cache key.
  33637. */
  33638. getOutputCacheKey() {
  33639. const renderer = this.renderer;
  33640. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  33641. }
  33642. /**
  33643. * Checks if the output configuration (tone mapping and color space) for
  33644. * the given target has changed.
  33645. *
  33646. * @param {Texture} outputTarget - The output target.
  33647. * @return {boolean} Whether the output configuration has changed or not.
  33648. */
  33649. hasOutputChange( outputTarget ) {
  33650. const cacheKey = _outputNodeMap.get( outputTarget );
  33651. return cacheKey !== this.getOutputCacheKey();
  33652. }
  33653. /**
  33654. * Returns a node that represents the output configuration (tone mapping and
  33655. * color space) for the current target.
  33656. *
  33657. * @param {Texture} outputTarget - The output target.
  33658. * @return {Node} The output node.
  33659. */
  33660. getOutputNode( outputTarget ) {
  33661. const renderer = this.renderer;
  33662. const cacheKey = this.getOutputCacheKey();
  33663. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  33664. _outputNodeMap.set( outputTarget, cacheKey );
  33665. return output;
  33666. }
  33667. /**
  33668. * Triggers the call of `updateBefore()` methods
  33669. * for all nodes of the given render object.
  33670. *
  33671. * @param {RenderObject} renderObject - The render object.
  33672. */
  33673. updateBefore( renderObject ) {
  33674. const nodeBuilder = renderObject.getNodeBuilderState();
  33675. for ( const node of nodeBuilder.updateBeforeNodes ) {
  33676. // update frame state for each node
  33677. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  33678. }
  33679. }
  33680. /**
  33681. * Triggers the call of `updateAfter()` methods
  33682. * for all nodes of the given render object.
  33683. *
  33684. * @param {RenderObject} renderObject - The render object.
  33685. */
  33686. updateAfter( renderObject ) {
  33687. const nodeBuilder = renderObject.getNodeBuilderState();
  33688. for ( const node of nodeBuilder.updateAfterNodes ) {
  33689. // update frame state for each node
  33690. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  33691. }
  33692. }
  33693. /**
  33694. * Triggers the call of `update()` methods
  33695. * for all nodes of the given compute node.
  33696. *
  33697. * @param {Node} computeNode - The compute node.
  33698. */
  33699. updateForCompute( computeNode ) {
  33700. const nodeFrame = this.getNodeFrame();
  33701. const nodeBuilder = this.getForCompute( computeNode );
  33702. for ( const node of nodeBuilder.updateNodes ) {
  33703. nodeFrame.updateNode( node );
  33704. }
  33705. }
  33706. /**
  33707. * Triggers the call of `update()` methods
  33708. * for all nodes of the given compute node.
  33709. *
  33710. * @param {RenderObject} renderObject - The render object.
  33711. */
  33712. updateForRender( renderObject ) {
  33713. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33714. const nodeBuilder = renderObject.getNodeBuilderState();
  33715. for ( const node of nodeBuilder.updateNodes ) {
  33716. nodeFrame.updateNode( node );
  33717. }
  33718. }
  33719. /**
  33720. * Returns `true` if the given render object requires a refresh.
  33721. *
  33722. * @param {RenderObject} renderObject - The render object.
  33723. * @return {boolean} Whether the given render object requires a refresh or not.
  33724. */
  33725. needsRefresh( renderObject ) {
  33726. const nodeFrame = this.getNodeFrameForRender( renderObject );
  33727. const monitor = renderObject.getMonitor();
  33728. return monitor.needsRefresh( renderObject, nodeFrame );
  33729. }
  33730. /**
  33731. * Frees the internal resources.
  33732. */
  33733. dispose() {
  33734. super.dispose();
  33735. this.nodeFrame = new NodeFrame();
  33736. this.nodeBuilderCache = new Map();
  33737. this.cacheLib = {};
  33738. }
  33739. }
  33740. const _plane = /*@__PURE__*/ new Plane();
  33741. /**
  33742. * Represents the state that is used to perform clipping via clipping planes.
  33743. * There is a default clipping context for each render context. When the
  33744. * scene holds instances of `ClippingGroup`, there will be a context for each
  33745. * group.
  33746. *
  33747. * @private
  33748. */
  33749. class ClippingContext {
  33750. /**
  33751. * Constructs a new clipping context.
  33752. *
  33753. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  33754. */
  33755. constructor( parentContext = null ) {
  33756. /**
  33757. * The clipping context's version.
  33758. *
  33759. * @type {number}
  33760. * @readonly
  33761. */
  33762. this.version = 0;
  33763. /**
  33764. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  33765. *
  33766. * @type {?boolean}
  33767. * @default null
  33768. */
  33769. this.clipIntersection = null;
  33770. /**
  33771. * The clipping context's cache key.
  33772. *
  33773. * @type {string}
  33774. */
  33775. this.cacheKey = '';
  33776. /**
  33777. * Whether the shadow pass is active or not.
  33778. *
  33779. * @type {boolean}
  33780. * @default false
  33781. */
  33782. this.shadowPass = false;
  33783. /**
  33784. * The view normal matrix.
  33785. *
  33786. * @type {Matrix3}
  33787. */
  33788. this.viewNormalMatrix = new Matrix3();
  33789. /**
  33790. * Internal cache for maintaining clipping contexts.
  33791. *
  33792. * @type {WeakMap<ClippingGroup,ClippingContext>}
  33793. */
  33794. this.clippingGroupContexts = new WeakMap();
  33795. /**
  33796. * The intersection planes.
  33797. *
  33798. * @type {Array<Vector4>}
  33799. */
  33800. this.intersectionPlanes = [];
  33801. /**
  33802. * The intersection planes.
  33803. *
  33804. * @type {Array<Vector4>}
  33805. */
  33806. this.unionPlanes = [];
  33807. /**
  33808. * The version of the clipping context's parent context.
  33809. *
  33810. * @type {?number}
  33811. * @readonly
  33812. */
  33813. this.parentVersion = null;
  33814. if ( parentContext !== null ) {
  33815. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  33816. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  33817. this.shadowPass = parentContext.shadowPass;
  33818. this.viewMatrix = parentContext.viewMatrix;
  33819. }
  33820. }
  33821. /**
  33822. * Projects the given source clipping planes and writes the result into the
  33823. * destination array.
  33824. *
  33825. * @param {Array<Plane>} source - The source clipping planes.
  33826. * @param {Array<Vector4>} destination - The destination.
  33827. * @param {number} offset - The offset.
  33828. */
  33829. projectPlanes( source, destination, offset ) {
  33830. const l = source.length;
  33831. for ( let i = 0; i < l; i ++ ) {
  33832. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  33833. const v = destination[ offset + i ];
  33834. const normal = _plane.normal;
  33835. v.x = - normal.x;
  33836. v.y = - normal.y;
  33837. v.z = - normal.z;
  33838. v.w = _plane.constant;
  33839. }
  33840. }
  33841. /**
  33842. * Updates the root clipping context of a scene.
  33843. *
  33844. * @param {Scene} scene - The scene.
  33845. * @param {Camera} camera - The camera that is used to render the scene.
  33846. */
  33847. updateGlobal( scene, camera ) {
  33848. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  33849. this.viewMatrix = camera.matrixWorldInverse;
  33850. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  33851. }
  33852. /**
  33853. * Updates the clipping context.
  33854. *
  33855. * @param {ClippingContext} parentContext - The parent context.
  33856. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  33857. */
  33858. update( parentContext, clippingGroup ) {
  33859. let update = false;
  33860. if ( parentContext.version !== this.parentVersion ) {
  33861. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  33862. this.unionPlanes = Array.from( parentContext.unionPlanes );
  33863. this.parentVersion = parentContext.version;
  33864. }
  33865. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  33866. this.clipIntersection = clippingGroup.clipIntersection;
  33867. if ( this.clipIntersection ) {
  33868. this.unionPlanes.length = parentContext.unionPlanes.length;
  33869. } else {
  33870. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  33871. }
  33872. }
  33873. const srcClippingPlanes = clippingGroup.clippingPlanes;
  33874. const l = srcClippingPlanes.length;
  33875. let dstClippingPlanes;
  33876. let offset;
  33877. if ( this.clipIntersection ) {
  33878. dstClippingPlanes = this.intersectionPlanes;
  33879. offset = parentContext.intersectionPlanes.length;
  33880. } else {
  33881. dstClippingPlanes = this.unionPlanes;
  33882. offset = parentContext.unionPlanes.length;
  33883. }
  33884. if ( dstClippingPlanes.length !== offset + l ) {
  33885. dstClippingPlanes.length = offset + l;
  33886. for ( let i = 0; i < l; i ++ ) {
  33887. dstClippingPlanes[ offset + i ] = new Vector4();
  33888. }
  33889. update = true;
  33890. }
  33891. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  33892. if ( update ) {
  33893. this.version ++;
  33894. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  33895. }
  33896. }
  33897. /**
  33898. * Returns a clipping context for the given clipping group.
  33899. *
  33900. * @param {ClippingGroup} clippingGroup - The clipping group.
  33901. * @return {ClippingContext} The clipping context.
  33902. */
  33903. getGroupContext( clippingGroup ) {
  33904. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  33905. let context = this.clippingGroupContexts.get( clippingGroup );
  33906. if ( context === undefined ) {
  33907. context = new ClippingContext( this );
  33908. this.clippingGroupContexts.set( clippingGroup, context );
  33909. }
  33910. context.update( this, clippingGroup );
  33911. return context;
  33912. }
  33913. /**
  33914. * The count of union clipping planes.
  33915. *
  33916. * @type {number}
  33917. * @readonly
  33918. */
  33919. get unionClippingCount() {
  33920. return this.unionPlanes.length;
  33921. }
  33922. }
  33923. /**
  33924. * This module is used to represent render bundles inside the renderer
  33925. * for further processing.
  33926. *
  33927. * @private
  33928. */
  33929. class RenderBundle {
  33930. /**
  33931. * Constructs a new bundle group.
  33932. *
  33933. * @param {BundleGroup} bundleGroup - The bundle group.
  33934. * @param {Camera} camera - The camera the bundle group is rendered with.
  33935. */
  33936. constructor( bundleGroup, camera ) {
  33937. this.bundleGroup = bundleGroup;
  33938. this.camera = camera;
  33939. }
  33940. }
  33941. const _chainKeys$1 = [];
  33942. /**
  33943. * This renderer module manages render bundles.
  33944. *
  33945. * @private
  33946. */
  33947. class RenderBundles {
  33948. /**
  33949. * Constructs a new render bundle management component.
  33950. */
  33951. constructor() {
  33952. /**
  33953. * A chain map for maintaining the render bundles.
  33954. *
  33955. * @type {ChainMap}
  33956. */
  33957. this.bundles = new ChainMap();
  33958. }
  33959. /**
  33960. * Returns a render bundle for the given bundle group and camera.
  33961. *
  33962. * @param {BundleGroup} bundleGroup - The bundle group.
  33963. * @param {Camera} camera - The camera the bundle group is rendered with.
  33964. * @return {RenderBundle} The render bundle.
  33965. */
  33966. get( bundleGroup, camera ) {
  33967. const bundles = this.bundles;
  33968. _chainKeys$1[ 0 ] = bundleGroup;
  33969. _chainKeys$1[ 1 ] = camera;
  33970. let bundle = bundles.get( _chainKeys$1 );
  33971. if ( bundle === undefined ) {
  33972. bundle = new RenderBundle( bundleGroup, camera );
  33973. bundles.set( _chainKeys$1, bundle );
  33974. }
  33975. _chainKeys$1.length = 0;
  33976. return bundle;
  33977. }
  33978. /**
  33979. * Frees all internal resources.
  33980. */
  33981. dispose() {
  33982. this.bundles = new ChainMap();
  33983. }
  33984. }
  33985. /**
  33986. * The purpose of a node library is to assign node implementations
  33987. * to existing library features. In `WebGPURenderer` lights, materials
  33988. * which are not based on `NodeMaterial` as well as tone mapping techniques
  33989. * are implemented with node-based modules.
  33990. *
  33991. * @private
  33992. */
  33993. class NodeLibrary {
  33994. /**
  33995. * Constructs a new node library.
  33996. */
  33997. constructor() {
  33998. /**
  33999. * A weak map that maps lights to light nodes.
  34000. *
  34001. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  34002. */
  34003. this.lightNodes = new WeakMap();
  34004. /**
  34005. * A map that maps materials to node materials.
  34006. *
  34007. * @type {Map<string,NodeMaterial.constructor>}
  34008. */
  34009. this.materialNodes = new Map();
  34010. /**
  34011. * A map that maps tone mapping techniques (constants)
  34012. * to tone mapping node functions.
  34013. *
  34014. * @type {Map<number,Function>}
  34015. */
  34016. this.toneMappingNodes = new Map();
  34017. }
  34018. /**
  34019. * Returns a matching node material instance for the given material object.
  34020. *
  34021. * This method also assigns/copies the properties of the given material object
  34022. * to the node material. This is done to make sure the current material
  34023. * configuration carries over to the node version.
  34024. *
  34025. * @param {Material} material - A material.
  34026. * @return {NodeMaterial} The corresponding node material.
  34027. */
  34028. fromMaterial( material ) {
  34029. if ( material.isNodeMaterial ) return material;
  34030. let nodeMaterial = null;
  34031. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  34032. if ( nodeMaterialClass !== null ) {
  34033. nodeMaterial = new nodeMaterialClass();
  34034. for ( const key in material ) {
  34035. nodeMaterial[ key ] = material[ key ];
  34036. }
  34037. }
  34038. return nodeMaterial;
  34039. }
  34040. /**
  34041. * Adds a tone mapping node function for a tone mapping technique (constant).
  34042. *
  34043. * @param {Function} toneMappingNode - The tone mapping node function.
  34044. * @param {number} toneMapping - The tone mapping.
  34045. */
  34046. addToneMapping( toneMappingNode, toneMapping ) {
  34047. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  34048. }
  34049. /**
  34050. * Returns a tone mapping node function for a tone mapping technique (constant).
  34051. *
  34052. * @param {number} toneMapping - The tone mapping.
  34053. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  34054. */
  34055. getToneMappingFunction( toneMapping ) {
  34056. return this.toneMappingNodes.get( toneMapping ) || null;
  34057. }
  34058. /**
  34059. * Returns a node material class definition for a material type.
  34060. *
  34061. * @param {string} materialType - The material type.
  34062. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  34063. */
  34064. getMaterialNodeClass( materialType ) {
  34065. return this.materialNodes.get( materialType ) || null;
  34066. }
  34067. /**
  34068. * Adds a node material class definition for a given material type.
  34069. *
  34070. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  34071. * @param {string} materialClassType - The material type.
  34072. */
  34073. addMaterial( materialNodeClass, materialClassType ) {
  34074. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  34075. }
  34076. /**
  34077. * Returns a light node class definition for a light class definition.
  34078. *
  34079. * @param {Light.constructor} light - The light class definition.
  34080. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  34081. */
  34082. getLightNodeClass( light ) {
  34083. return this.lightNodes.get( light ) || null;
  34084. }
  34085. /**
  34086. * Adds a light node class definition for a given light class definition.
  34087. *
  34088. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  34089. * @param {Light.constructor} lightClass - The light class definition.
  34090. */
  34091. addLight( lightNodeClass, lightClass ) {
  34092. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  34093. }
  34094. /**
  34095. * Adds a node class definition for the given type to the provided type library.
  34096. *
  34097. * @param {any} nodeClass - The node class definition.
  34098. * @param {number|string} type - The object type.
  34099. * @param {Map} library - The type library.
  34100. */
  34101. addType( nodeClass, type, library ) {
  34102. if ( library.has( type ) ) {
  34103. console.warn( `Redefinition of node ${ type }` );
  34104. return;
  34105. }
  34106. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  34107. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  34108. library.set( type, nodeClass );
  34109. }
  34110. /**
  34111. * Adds a node class definition for the given class definition to the provided type library.
  34112. *
  34113. * @param {any} nodeClass - The node class definition.
  34114. * @param {any} baseClass - The class definition.
  34115. * @param {WeakMap} library - The type library.
  34116. */
  34117. addClass( nodeClass, baseClass, library ) {
  34118. if ( library.has( baseClass ) ) {
  34119. console.warn( `Redefinition of node ${ baseClass.name }` );
  34120. return;
  34121. }
  34122. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  34123. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  34124. library.set( baseClass, nodeClass );
  34125. }
  34126. }
  34127. const _defaultLights = /*@__PURE__*/ new LightsNode();
  34128. const _chainKeys = [];
  34129. /**
  34130. * This renderer module manages the lights nodes which are unique
  34131. * per scene and camera combination.
  34132. *
  34133. * The lights node itself is later configured in the render list
  34134. * with the actual lights from the scene.
  34135. *
  34136. * @private
  34137. * @augments ChainMap
  34138. */
  34139. class Lighting extends ChainMap {
  34140. /**
  34141. * Constructs a lighting management component.
  34142. */
  34143. constructor() {
  34144. super();
  34145. }
  34146. /**
  34147. * Creates a new lights node for the given array of lights.
  34148. *
  34149. * @param {Array<Light>} lights - The render object.
  34150. * @return {LightsNode} The lights node.
  34151. */
  34152. createNode( lights = [] ) {
  34153. return new LightsNode().setLights( lights );
  34154. }
  34155. /**
  34156. * Returns a lights node for the given scene and camera.
  34157. *
  34158. * @param {Scene} scene - The scene.
  34159. * @param {Camera} camera - The camera.
  34160. * @return {LightsNode} The lights node.
  34161. */
  34162. getNode( scene, camera ) {
  34163. // ignore post-processing
  34164. if ( scene.isQuadMesh ) return _defaultLights;
  34165. _chainKeys[ 0 ] = scene;
  34166. _chainKeys[ 1 ] = camera;
  34167. let node = this.get( _chainKeys );
  34168. if ( node === undefined ) {
  34169. node = this.createNode();
  34170. this.set( _chainKeys, node );
  34171. }
  34172. _chainKeys.length = 0;
  34173. return node;
  34174. }
  34175. }
  34176. /**
  34177. * A special type of render target that is used when rendering
  34178. * with the WebXR Device API.
  34179. *
  34180. * @private
  34181. * @augments RenderTarget
  34182. */
  34183. class XRRenderTarget extends RenderTarget {
  34184. /**
  34185. * Constructs a new XR render target.
  34186. *
  34187. * @param {number} [width=1] - The width of the render target.
  34188. * @param {number} [height=1] - The height of the render target.
  34189. * @param {Object} [options={}] - The configuration options.
  34190. */
  34191. constructor( width = 1, height = 1, options = {} ) {
  34192. super( width, height, options );
  34193. /**
  34194. * This flag can be used for type testing.
  34195. *
  34196. * @type {boolean}
  34197. * @readonly
  34198. * @default true
  34199. */
  34200. this.isXRRenderTarget = true;
  34201. /**
  34202. * Whether the attachments of the render target
  34203. * are defined by external textures. This flag is
  34204. * set to `true` when using the WebXR Layers API.
  34205. *
  34206. * @type {boolean}
  34207. * @default false
  34208. */
  34209. this.hasExternalTextures = false;
  34210. /**
  34211. * Whether a depth buffer should automatically be allocated
  34212. * for this XR render target or not.
  34213. *
  34214. * Allocating a depth buffer is the default behavior of XR render
  34215. * targets. However, when using the WebXR Layers API, this flag
  34216. * must be set to `false` when the `ignoreDepthValues` property of
  34217. * the projection layers evaluates to `false`.
  34218. *
  34219. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  34220. *
  34221. * @type {boolean}
  34222. * @default true
  34223. */
  34224. this.autoAllocateDepthBuffer = true;
  34225. }
  34226. copy( source ) {
  34227. super.copy( source );
  34228. this.hasExternalTextures = source.hasExternalTextures;
  34229. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  34230. return this;
  34231. }
  34232. }
  34233. const _cameraLPos = /*@__PURE__*/ new Vector3();
  34234. const _cameraRPos = /*@__PURE__*/ new Vector3();
  34235. /**
  34236. * The XR manager is built on top of the WebXR Device API to
  34237. * manage XR sessions with `WebGPURenderer`.
  34238. *
  34239. * XR is currently only supported with a WebGL 2 backend.
  34240. *
  34241. * @augments EventDispatcher
  34242. */
  34243. class XRManager extends EventDispatcher {
  34244. /**
  34245. * Constructs a new XR manager.
  34246. *
  34247. * @param {Renderer} renderer - The renderer.
  34248. */
  34249. constructor( renderer ) {
  34250. super();
  34251. /**
  34252. * This flag globally enables XR rendering.
  34253. *
  34254. * @type {boolean}
  34255. * @default false
  34256. */
  34257. this.enabled = false;
  34258. /**
  34259. * Whether the XR device is currently presenting or not.
  34260. *
  34261. * @type {boolean}
  34262. * @default false
  34263. * @readonly
  34264. */
  34265. this.isPresenting = false;
  34266. /**
  34267. * Whether the XR camera should automatically be updated or not.
  34268. *
  34269. * @type {boolean}
  34270. * @default true
  34271. */
  34272. this.cameraAutoUpdate = true;
  34273. /**
  34274. * The renderer.
  34275. *
  34276. * @private
  34277. * @type {Renderer}
  34278. */
  34279. this._renderer = renderer;
  34280. // camera
  34281. /**
  34282. * Represents the camera for the left eye.
  34283. *
  34284. * @private
  34285. * @type {PerspectiveCamera}
  34286. */
  34287. this._cameraL = new PerspectiveCamera();
  34288. this._cameraL.viewport = new Vector4();
  34289. /**
  34290. * Represents the camera for the right eye.
  34291. *
  34292. * @private
  34293. * @type {PerspectiveCamera}
  34294. */
  34295. this._cameraR = new PerspectiveCamera();
  34296. this._cameraR.viewport = new Vector4();
  34297. /**
  34298. * A list of cameras used for rendering the XR views.
  34299. *
  34300. * @private
  34301. * @type {Array<Camera>}
  34302. */
  34303. this._cameras = [ this._cameraL, this._cameraR ];
  34304. /**
  34305. * The main XR camera.
  34306. *
  34307. * @private
  34308. * @type {ArrayCamera}
  34309. */
  34310. this._cameraXR = new ArrayCamera();
  34311. /**
  34312. * The current near value of the XR camera.
  34313. *
  34314. * @private
  34315. * @type {?number}
  34316. * @default null
  34317. */
  34318. this._currentDepthNear = null;
  34319. /**
  34320. * The current far value of the XR camera.
  34321. *
  34322. * @private
  34323. * @type {?number}
  34324. * @default null
  34325. */
  34326. this._currentDepthFar = null;
  34327. /**
  34328. * A list of WebXR controllers requested by the application.
  34329. *
  34330. * @private
  34331. * @type {Array<WebXRController>}
  34332. */
  34333. this._controllers = [];
  34334. /**
  34335. * A list of XR input source. Each input source belongs to
  34336. * an instance of WebXRController.
  34337. *
  34338. * @private
  34339. * @type {Array<XRInputSource?>}
  34340. */
  34341. this._controllerInputSources = [];
  34342. /**
  34343. * The XR render target that represents the rendering destination
  34344. * during an active XR session.
  34345. *
  34346. * @private
  34347. * @type {?RenderTarget}
  34348. * @default null
  34349. */
  34350. this._xrRenderTarget = null;
  34351. /**
  34352. * An array holding all the non-projection layers
  34353. *
  34354. * @private
  34355. * @type {Array<Object>}
  34356. * @default []
  34357. */
  34358. this._layers = [];
  34359. /**
  34360. * Whether the device has support for all layer types.
  34361. *
  34362. * @type {boolean}
  34363. * @default false
  34364. */
  34365. this._supportsLayers = false;
  34366. /**
  34367. * Helper function to create native WebXR Layer.
  34368. *
  34369. * @private
  34370. * @type {Function}
  34371. */
  34372. this._createXRLayer = createXRLayer.bind( this );
  34373. /**
  34374. * The current WebGL context.
  34375. *
  34376. * @private
  34377. * @type {?WebGL2RenderingContext}
  34378. * @default null
  34379. */
  34380. this._gl = null;
  34381. /**
  34382. * The current animation context.
  34383. *
  34384. * @private
  34385. * @type {?Window}
  34386. * @default null
  34387. */
  34388. this._currentAnimationContext = null;
  34389. /**
  34390. * The current animation loop.
  34391. *
  34392. * @private
  34393. * @type {?Function}
  34394. * @default null
  34395. */
  34396. this._currentAnimationLoop = null;
  34397. /**
  34398. * The current pixel ratio.
  34399. *
  34400. * @private
  34401. * @type {?number}
  34402. * @default null
  34403. */
  34404. this._currentPixelRatio = null;
  34405. /**
  34406. * The current size of the renderer's canvas
  34407. * in logical pixel unit.
  34408. *
  34409. * @private
  34410. * @type {Vector2}
  34411. */
  34412. this._currentSize = new Vector2();
  34413. /**
  34414. * The default event listener for handling events inside a XR session.
  34415. *
  34416. * @private
  34417. * @type {Function}
  34418. */
  34419. this._onSessionEvent = onSessionEvent.bind( this );
  34420. /**
  34421. * The event listener for handling the end of a XR session.
  34422. *
  34423. * @private
  34424. * @type {Function}
  34425. */
  34426. this._onSessionEnd = onSessionEnd.bind( this );
  34427. /**
  34428. * The event listener for handling the `inputsourceschange` event.
  34429. *
  34430. * @private
  34431. * @type {Function}
  34432. */
  34433. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  34434. /**
  34435. * The animation loop which is used as a replacement for the default
  34436. * animation loop of the application. It is only used when a XR session
  34437. * is active.
  34438. *
  34439. * @private
  34440. * @type {Function}
  34441. */
  34442. this._onAnimationFrame = onAnimationFrame.bind( this );
  34443. /**
  34444. * The current XR reference space.
  34445. *
  34446. * @private
  34447. * @type {?XRReferenceSpace}
  34448. * @default null
  34449. */
  34450. this._referenceSpace = null;
  34451. /**
  34452. * The current XR reference space type.
  34453. *
  34454. * @private
  34455. * @type {XRReferenceSpaceType}
  34456. * @default 'local-floor'
  34457. */
  34458. this._referenceSpaceType = 'local-floor';
  34459. /**
  34460. * A custom reference space defined by the application.
  34461. *
  34462. * @private
  34463. * @type {?XRReferenceSpace}
  34464. * @default null
  34465. */
  34466. this._customReferenceSpace = null;
  34467. /**
  34468. * The framebuffer scale factor.
  34469. *
  34470. * @private
  34471. * @type {number}
  34472. * @default 1
  34473. */
  34474. this._framebufferScaleFactor = 1;
  34475. /**
  34476. * The foveation factor.
  34477. *
  34478. * @private
  34479. * @type {number}
  34480. * @default 1
  34481. */
  34482. this._foveation = 1.0;
  34483. /**
  34484. * A reference to the current XR session.
  34485. *
  34486. * @private
  34487. * @type {?XRSession}
  34488. * @default null
  34489. */
  34490. this._session = null;
  34491. /**
  34492. * A reference to the current XR base layer.
  34493. *
  34494. * @private
  34495. * @type {?XRWebGLLayer}
  34496. * @default null
  34497. */
  34498. this._glBaseLayer = null;
  34499. /**
  34500. * A reference to the current XR binding.
  34501. *
  34502. * @private
  34503. * @type {?XRWebGLBinding}
  34504. * @default null
  34505. */
  34506. this._glBinding = null;
  34507. /**
  34508. * A reference to the current XR projection layer.
  34509. *
  34510. * @private
  34511. * @type {?XRProjectionLayer}
  34512. * @default null
  34513. */
  34514. this._glProjLayer = null;
  34515. /**
  34516. * A reference to the current XR frame.
  34517. *
  34518. * @private
  34519. * @type {?XRFrame}
  34520. * @default null
  34521. */
  34522. this._xrFrame = null;
  34523. /**
  34524. * Whether to use the WebXR Layers API or not.
  34525. *
  34526. * @private
  34527. * @type {boolean}
  34528. * @readonly
  34529. */
  34530. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  34531. }
  34532. /**
  34533. * Returns an instance of `THREE.Group` that represents the transformation
  34534. * of a XR controller in target ray space. The requested controller is defined
  34535. * by the given index.
  34536. *
  34537. * @param {number} index - The index of the XR controller.
  34538. * @return {Group} A group that represents the controller's transformation.
  34539. */
  34540. getController( index ) {
  34541. const controller = this._getController( index );
  34542. return controller.getTargetRaySpace();
  34543. }
  34544. /**
  34545. * Returns an instance of `THREE.Group` that represents the transformation
  34546. * of a XR controller in grip space. The requested controller is defined
  34547. * by the given index.
  34548. *
  34549. * @param {number} index - The index of the XR controller.
  34550. * @return {Group} A group that represents the controller's transformation.
  34551. */
  34552. getControllerGrip( index ) {
  34553. const controller = this._getController( index );
  34554. return controller.getGripSpace();
  34555. }
  34556. /**
  34557. * Returns an instance of `THREE.Group` that represents the transformation
  34558. * of a XR controller in hand space. The requested controller is defined
  34559. * by the given index.
  34560. *
  34561. * @param {number} index - The index of the XR controller.
  34562. * @return {Group} A group that represents the controller's transformation.
  34563. */
  34564. getHand( index ) {
  34565. const controller = this._getController( index );
  34566. return controller.getHandSpace();
  34567. }
  34568. /**
  34569. * Returns the foveation value.
  34570. *
  34571. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  34572. */
  34573. getFoveation() {
  34574. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  34575. return undefined;
  34576. }
  34577. return this._foveation;
  34578. }
  34579. /**
  34580. * Sets the foveation value.
  34581. *
  34582. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  34583. * and `1` means maximum foveation (the edges render at lower resolution).
  34584. */
  34585. setFoveation( foveation ) {
  34586. this._foveation = foveation;
  34587. if ( this._glProjLayer !== null ) {
  34588. this._glProjLayer.fixedFoveation = foveation;
  34589. }
  34590. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  34591. this._glBaseLayer.fixedFoveation = foveation;
  34592. }
  34593. }
  34594. /**
  34595. * Returns the framebuffer scale factor.
  34596. *
  34597. * @return {number} The framebuffer scale factor.
  34598. */
  34599. getFramebufferScaleFactor() {
  34600. return this._framebufferScaleFactor;
  34601. }
  34602. /**
  34603. * Sets the framebuffer scale factor.
  34604. *
  34605. * This method can not be used during a XR session.
  34606. *
  34607. * @param {number} factor - The framebuffer scale factor.
  34608. */
  34609. setFramebufferScaleFactor( factor ) {
  34610. this._framebufferScaleFactor = factor;
  34611. if ( this.isPresenting === true ) {
  34612. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  34613. }
  34614. }
  34615. /**
  34616. * Returns the reference space type.
  34617. *
  34618. * @return {XRReferenceSpaceType} The reference space type.
  34619. */
  34620. getReferenceSpaceType() {
  34621. return this._referenceSpaceType;
  34622. }
  34623. /**
  34624. * Sets the reference space type.
  34625. *
  34626. * This method can not be used during a XR session.
  34627. *
  34628. * @param {XRReferenceSpaceType} type - The reference space type.
  34629. */
  34630. setReferenceSpaceType( type ) {
  34631. this._referenceSpaceType = type;
  34632. if ( this.isPresenting === true ) {
  34633. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  34634. }
  34635. }
  34636. /**
  34637. * Returns the XR reference space.
  34638. *
  34639. * @return {XRReferenceSpace} The XR reference space.
  34640. */
  34641. getReferenceSpace() {
  34642. return this._customReferenceSpace || this._referenceSpace;
  34643. }
  34644. /**
  34645. * Sets a custom XR reference space.
  34646. *
  34647. * @param {XRReferenceSpace} space - The XR reference space.
  34648. */
  34649. setReferenceSpace( space ) {
  34650. this._customReferenceSpace = space;
  34651. }
  34652. /**
  34653. * Returns the XR camera.
  34654. *
  34655. * @return {ArrayCamera} The XR camera.
  34656. */
  34657. getCamera() {
  34658. return this._cameraXR;
  34659. }
  34660. /**
  34661. * Returns the environment blend mode from the current XR session.
  34662. *
  34663. * @return {?('opaque'|'additive'|'alpha-blend')} The environment blend mode. Returns `null` when used outside of a XR session.
  34664. */
  34665. getEnvironmentBlendMode() {
  34666. if ( this._session !== null ) {
  34667. return this._session.environmentBlendMode;
  34668. }
  34669. }
  34670. /**
  34671. * Returns the current XR frame.
  34672. *
  34673. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  34674. */
  34675. getFrame() {
  34676. return this._xrFrame;
  34677. }
  34678. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = [] ) {
  34679. const geometry = new PlaneGeometry( width, height );
  34680. const renderTarget = new XRRenderTarget(
  34681. pixelwidth,
  34682. pixelheight,
  34683. {
  34684. format: RGBAFormat,
  34685. type: UnsignedByteType,
  34686. depthTexture: new DepthTexture(
  34687. pixelwidth,
  34688. pixelheight,
  34689. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  34690. undefined,
  34691. undefined,
  34692. undefined,
  34693. undefined,
  34694. undefined,
  34695. undefined,
  34696. attributes.stencil ? DepthStencilFormat : DepthFormat
  34697. ),
  34698. stencilBuffer: attributes.stencil,
  34699. resolveDepthBuffer: false,
  34700. resolveStencilBuffer: false
  34701. } );
  34702. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  34703. material.map = renderTarget.texture;
  34704. material.map.offset.y = 1;
  34705. material.map.repeat.y = -1;
  34706. const plane = new Mesh( geometry, material );
  34707. plane.position.copy( translation );
  34708. plane.quaternion.copy( quaternion );
  34709. const layer = {
  34710. type: 'quad',
  34711. width: width,
  34712. height: height,
  34713. translation: translation,
  34714. quaternion: quaternion,
  34715. pixelwidth: pixelwidth,
  34716. pixelheight: pixelheight,
  34717. plane: plane,
  34718. material: material,
  34719. rendercall: rendercall,
  34720. renderTarget: renderTarget };
  34721. this._layers.push( layer );
  34722. if ( this._session !== null ) {
  34723. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  34724. layer.plane.material.blending = CustomBlending;
  34725. layer.plane.material.blendEquation = AddEquation;
  34726. layer.plane.material.blendSrc = ZeroFactor;
  34727. layer.plane.material.blendDst = ZeroFactor;
  34728. layer.xrlayer = this._createXRLayer( layer );
  34729. const xrlayers = this._session.renderState.layers;
  34730. xrlayers.unshift( layer.xrlayer );
  34731. this._session.updateRenderState( { layers: xrlayers } );
  34732. } else {
  34733. renderTarget.isXRRenderTarget = false;
  34734. }
  34735. return plane;
  34736. }
  34737. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = [] ) {
  34738. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  34739. const renderTarget = new XRRenderTarget(
  34740. pixelwidth,
  34741. pixelheight,
  34742. {
  34743. format: RGBAFormat,
  34744. type: UnsignedByteType,
  34745. depthTexture: new DepthTexture(
  34746. pixelwidth,
  34747. pixelheight,
  34748. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  34749. undefined,
  34750. undefined,
  34751. undefined,
  34752. undefined,
  34753. undefined,
  34754. undefined,
  34755. attributes.stencil ? DepthStencilFormat : DepthFormat
  34756. ),
  34757. stencilBuffer: attributes.stencil,
  34758. resolveDepthBuffer: false,
  34759. resolveStencilBuffer: false
  34760. } );
  34761. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  34762. material.map = renderTarget.texture;
  34763. material.map.offset.y = 1;
  34764. material.map.repeat.y = -1;
  34765. const plane = new Mesh( geometry, material );
  34766. plane.position.copy( translation );
  34767. plane.quaternion.copy( quaternion );
  34768. const layer = {
  34769. type: 'cylinder',
  34770. radius: radius,
  34771. centralAngle: centralAngle,
  34772. aspectratio: aspectratio,
  34773. translation: translation,
  34774. quaternion: quaternion,
  34775. pixelwidth: pixelwidth,
  34776. pixelheight: pixelheight,
  34777. plane: plane,
  34778. material: material,
  34779. rendercall: rendercall,
  34780. renderTarget: renderTarget };
  34781. this._layers.push( layer );
  34782. if ( this._session !== null ) {
  34783. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  34784. layer.plane.material.blending = CustomBlending;
  34785. layer.plane.material.blendEquation = AddEquation;
  34786. layer.plane.material.blendSrc = ZeroFactor;
  34787. layer.plane.material.blendDst = ZeroFactor;
  34788. layer.xrlayer = this._createXRLayer( layer );
  34789. const xrlayers = this._session.renderState.layers;
  34790. xrlayers.unshift( layer.xrlayer );
  34791. this._session.updateRenderState( { layers: xrlayers } );
  34792. } else {
  34793. renderTarget.isXRRenderTarget = false;
  34794. }
  34795. return plane;
  34796. }
  34797. renderLayers( ) {
  34798. const translationObject = new Vector3();
  34799. const quaternionObject = new Quaternion();
  34800. const wasPresenting = this.isPresenting;
  34801. this.isPresenting = false;
  34802. for ( const layer of this._layers ) {
  34803. layer.renderTarget.isXRRenderTarget = this._session !== null;
  34804. layer.renderTarget.hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  34805. layer.renderTarget.autoAllocateDepthBuffer = ! layer.renderTarget.isXRRenderTarget;
  34806. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  34807. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  34808. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  34809. this._renderer.backend.setXRRenderTargetTextures(
  34810. layer.renderTarget,
  34811. glSubImage.colorTexture,
  34812. glSubImage.depthStencilTexture );
  34813. }
  34814. this._renderer.setRenderTarget( layer.renderTarget );
  34815. layer.rendercall();
  34816. }
  34817. this.isPresenting = wasPresenting;
  34818. this._renderer.setRenderTarget( null );
  34819. }
  34820. /**
  34821. * Returns the current XR session.
  34822. *
  34823. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  34824. */
  34825. getSession() {
  34826. return this._session;
  34827. }
  34828. /**
  34829. * After a XR session has been requested usually with one of the `*Button` modules, it
  34830. * is injected into the renderer with this method. This method triggers the start of
  34831. * the actual XR rendering.
  34832. *
  34833. * @async
  34834. * @param {XRSession} session - The XR session to set.
  34835. * @return {Promise} A Promise that resolves when the session has been set.
  34836. */
  34837. async setSession( session ) {
  34838. const renderer = this._renderer;
  34839. const backend = renderer.backend;
  34840. this._gl = renderer.getContext();
  34841. const gl = this._gl;
  34842. const attributes = gl.getContextAttributes();
  34843. this._session = session;
  34844. if ( session !== null ) {
  34845. 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.' );
  34846. session.addEventListener( 'select', this._onSessionEvent );
  34847. session.addEventListener( 'selectstart', this._onSessionEvent );
  34848. session.addEventListener( 'selectend', this._onSessionEvent );
  34849. session.addEventListener( 'squeeze', this._onSessionEvent );
  34850. session.addEventListener( 'squeezestart', this._onSessionEvent );
  34851. session.addEventListener( 'squeezeend', this._onSessionEvent );
  34852. session.addEventListener( 'end', this._onSessionEnd );
  34853. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  34854. await backend.makeXRCompatible();
  34855. this._currentPixelRatio = renderer.getPixelRatio();
  34856. renderer.getSize( this._currentSize );
  34857. this._currentAnimationContext = renderer._animation.getContext();
  34858. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  34859. renderer._animation.stop();
  34860. //
  34861. if ( this._useLayers === true ) {
  34862. // default path using XRWebGLBinding/XRProjectionLayer
  34863. let depthFormat = null;
  34864. let depthType = null;
  34865. let glDepthFormat = null;
  34866. if ( renderer.depth ) {
  34867. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  34868. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  34869. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  34870. }
  34871. const projectionlayerInit = {
  34872. colorFormat: gl.RGBA8,
  34873. depthFormat: glDepthFormat,
  34874. scaleFactor: this._framebufferScaleFactor
  34875. };
  34876. const glBinding = new XRWebGLBinding( session, gl );
  34877. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  34878. const layersArray = [ glProjLayer ];
  34879. this._glBinding = glBinding;
  34880. this._glProjLayer = glProjLayer;
  34881. renderer.setPixelRatio( 1 );
  34882. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  34883. this._xrRenderTarget = new XRRenderTarget(
  34884. glProjLayer.textureWidth,
  34885. glProjLayer.textureHeight,
  34886. {
  34887. format: RGBAFormat,
  34888. type: UnsignedByteType,
  34889. colorSpace: renderer.outputColorSpace,
  34890. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  34891. stencilBuffer: renderer.stencil,
  34892. samples: attributes.antialias ? 4 : 0,
  34893. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  34894. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  34895. } );
  34896. this._xrRenderTarget.hasExternalTextures = true;
  34897. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  34898. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  34899. if ( this._supportsLayers ) {
  34900. // switch layers to native
  34901. for ( const layer of this._layers ) {
  34902. // change material so it "punches" out a hole to show the XR Layer.
  34903. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  34904. layer.plane.material.blending = CustomBlending;
  34905. layer.plane.material.blendEquation = AddEquation;
  34906. layer.plane.material.blendSrc = ZeroFactor;
  34907. layer.plane.material.blendDst = ZeroFactor;
  34908. layer.xrlayer = this._createXRLayer( layer );
  34909. layersArray.unshift( layer.xrlayer );
  34910. }
  34911. }
  34912. session.updateRenderState( { layers: layersArray } );
  34913. } else {
  34914. // fallback to XRWebGLLayer
  34915. const layerInit = {
  34916. antialias: renderer.samples > 0,
  34917. alpha: true,
  34918. depth: renderer.depth,
  34919. stencil: renderer.stencil,
  34920. framebufferScaleFactor: this.getFramebufferScaleFactor()
  34921. };
  34922. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  34923. this._glBaseLayer = glBaseLayer;
  34924. session.updateRenderState( { baseLayer: glBaseLayer } );
  34925. renderer.setPixelRatio( 1 );
  34926. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  34927. this._xrRenderTarget = new XRRenderTarget(
  34928. glBaseLayer.framebufferWidth,
  34929. glBaseLayer.framebufferHeight,
  34930. {
  34931. format: RGBAFormat,
  34932. type: UnsignedByteType,
  34933. colorSpace: renderer.outputColorSpace,
  34934. stencilBuffer: renderer.stencil,
  34935. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  34936. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  34937. }
  34938. );
  34939. }
  34940. //
  34941. this.setFoveation( this.getFoveation() );
  34942. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  34943. renderer._animation.setContext( session );
  34944. renderer._animation.start();
  34945. this.isPresenting = true;
  34946. this.dispatchEvent( { type: 'sessionstart' } );
  34947. }
  34948. }
  34949. /**
  34950. * This method is called by the renderer per frame and updates the XR camera
  34951. * and it sub cameras based on the given camera. The given camera is the "user"
  34952. * camera created on application level and used for non-XR rendering.
  34953. *
  34954. * @param {PerspectiveCamera} camera - The camera.
  34955. */
  34956. updateCamera( camera ) {
  34957. const session = this._session;
  34958. if ( session === null ) return;
  34959. const depthNear = camera.near;
  34960. const depthFar = camera.far;
  34961. const cameraXR = this._cameraXR;
  34962. const cameraL = this._cameraL;
  34963. const cameraR = this._cameraR;
  34964. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  34965. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  34966. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  34967. // Note that the new renderState won't apply until the next frame. See #18320
  34968. session.updateRenderState( {
  34969. depthNear: cameraXR.near,
  34970. depthFar: cameraXR.far
  34971. } );
  34972. this._currentDepthNear = cameraXR.near;
  34973. this._currentDepthFar = cameraXR.far;
  34974. }
  34975. cameraL.layers.mask = camera.layers.mask | 0b010;
  34976. cameraR.layers.mask = camera.layers.mask | 0b100;
  34977. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  34978. const parent = camera.parent;
  34979. const cameras = cameraXR.cameras;
  34980. updateCamera( cameraXR, parent );
  34981. for ( let i = 0; i < cameras.length; i ++ ) {
  34982. updateCamera( cameras[ i ], parent );
  34983. }
  34984. // update projection matrix for proper view frustum culling
  34985. if ( cameras.length === 2 ) {
  34986. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  34987. } else {
  34988. // assume single camera setup (AR)
  34989. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  34990. }
  34991. // update user camera and its children
  34992. updateUserCamera( camera, cameraXR, parent );
  34993. }
  34994. /**
  34995. * Returns a WebXR controller for the given controller index.
  34996. *
  34997. * @private
  34998. * @param {number} index - The controller index.
  34999. * @return {WebXRController} The XR controller.
  35000. */
  35001. _getController( index ) {
  35002. let controller = this._controllers[ index ];
  35003. if ( controller === undefined ) {
  35004. controller = new WebXRController();
  35005. this._controllers[ index ] = controller;
  35006. }
  35007. return controller;
  35008. }
  35009. }
  35010. /**
  35011. * Assumes 2 cameras that are parallel and share an X-axis, and that
  35012. * the cameras' projection and world matrices have already been set.
  35013. * And that near and far planes are identical for both cameras.
  35014. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  35015. *
  35016. * @param {ArrayCamera} camera - The camera to update.
  35017. * @param {PerspectiveCamera} cameraL - The left camera.
  35018. * @param {PerspectiveCamera} cameraR - The right camera.
  35019. */
  35020. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  35021. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  35022. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  35023. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  35024. const projL = cameraL.projectionMatrix.elements;
  35025. const projR = cameraR.projectionMatrix.elements;
  35026. // VR systems will have identical far and near planes, and
  35027. // most likely identical top and bottom frustum extents.
  35028. // Use the left camera for these values.
  35029. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  35030. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  35031. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  35032. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  35033. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  35034. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  35035. const left = near * leftFov;
  35036. const right = near * rightFov;
  35037. // Calculate the new camera's position offset from the
  35038. // left camera. xOffset should be roughly half `ipd`.
  35039. const zOffset = ipd / ( - leftFov + rightFov );
  35040. const xOffset = zOffset * - leftFov;
  35041. // TODO: Better way to apply this offset?
  35042. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  35043. camera.translateX( xOffset );
  35044. camera.translateZ( zOffset );
  35045. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  35046. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  35047. // Check if the projection uses an infinite far plane.
  35048. if ( projL[ 10 ] === -1 ) {
  35049. // Use the projection matrix from the left eye.
  35050. // The camera offset is sufficient to include the view volumes
  35051. // of both eyes (assuming symmetric projections).
  35052. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  35053. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  35054. } else {
  35055. // Find the union of the frustum values of the cameras and scale
  35056. // the values so that the near plane's position does not change in world space,
  35057. // although must now be relative to the new union camera.
  35058. const near2 = near + zOffset;
  35059. const far2 = far + zOffset;
  35060. const left2 = left - xOffset;
  35061. const right2 = right + ( ipd - xOffset );
  35062. const top2 = topFov * far / far2 * near2;
  35063. const bottom2 = bottomFov * far / far2 * near2;
  35064. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  35065. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  35066. }
  35067. }
  35068. /**
  35069. * Updates the world matrices for the given camera based on the parent 3D object.
  35070. *
  35071. * @inner
  35072. * @param {Camera} camera - The camera to update.
  35073. * @param {Object3D} parent - The parent 3D object.
  35074. */
  35075. function updateCamera( camera, parent ) {
  35076. if ( parent === null ) {
  35077. camera.matrixWorld.copy( camera.matrix );
  35078. } else {
  35079. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  35080. }
  35081. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  35082. }
  35083. /**
  35084. * Updates the given camera with the transformation of the XR camera and parent object.
  35085. *
  35086. * @inner
  35087. * @param {Camera} camera - The camera to update.
  35088. * @param {ArrayCamera} cameraXR - The XR camera.
  35089. * @param {Object3D} parent - The parent 3D object.
  35090. */
  35091. function updateUserCamera( camera, cameraXR, parent ) {
  35092. if ( parent === null ) {
  35093. camera.matrix.copy( cameraXR.matrixWorld );
  35094. } else {
  35095. camera.matrix.copy( parent.matrixWorld );
  35096. camera.matrix.invert();
  35097. camera.matrix.multiply( cameraXR.matrixWorld );
  35098. }
  35099. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  35100. camera.updateMatrixWorld( true );
  35101. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  35102. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  35103. if ( camera.isPerspectiveCamera ) {
  35104. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  35105. camera.zoom = 1;
  35106. }
  35107. }
  35108. function onSessionEvent( event ) {
  35109. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  35110. if ( controllerIndex === -1 ) {
  35111. return;
  35112. }
  35113. const controller = this._controllers[ controllerIndex ];
  35114. if ( controller !== undefined ) {
  35115. const referenceSpace = this.getReferenceSpace();
  35116. controller.update( event.inputSource, event.frame, referenceSpace );
  35117. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  35118. }
  35119. }
  35120. function onSessionEnd() {
  35121. const session = this._session;
  35122. const renderer = this._renderer;
  35123. session.removeEventListener( 'select', this._onSessionEvent );
  35124. session.removeEventListener( 'selectstart', this._onSessionEvent );
  35125. session.removeEventListener( 'selectend', this._onSessionEvent );
  35126. session.removeEventListener( 'squeeze', this._onSessionEvent );
  35127. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  35128. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  35129. session.removeEventListener( 'end', this._onSessionEnd );
  35130. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  35131. for ( let i = 0; i < this._controllers.length; i ++ ) {
  35132. const inputSource = this._controllerInputSources[ i ];
  35133. if ( inputSource === null ) continue;
  35134. this._controllerInputSources[ i ] = null;
  35135. this._controllers[ i ].disconnect( inputSource );
  35136. }
  35137. this._currentDepthNear = null;
  35138. this._currentDepthFar = null;
  35139. // restore framebuffer/rendering state
  35140. renderer.backend.setXRTarget( null );
  35141. renderer.setOutputRenderTarget( null );
  35142. renderer.setRenderTarget( null );
  35143. this._session = null;
  35144. this._xrRenderTarget = null;
  35145. // switch layers back to emulated
  35146. if ( this._supportsLayers === true ) {
  35147. for ( const layer of this._layers ) {
  35148. // Recreate layer render target to reset state
  35149. layer.renderTarget = new XRRenderTarget(
  35150. layer.pixelwidth,
  35151. layer.pixelheight,
  35152. {
  35153. format: RGBAFormat,
  35154. type: UnsignedByteType,
  35155. depthTexture: new DepthTexture(
  35156. layer.pixelwidth,
  35157. layer.pixelheight,
  35158. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  35159. undefined,
  35160. undefined,
  35161. undefined,
  35162. undefined,
  35163. undefined,
  35164. undefined,
  35165. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  35166. ),
  35167. stencilBuffer: layer.stencilBuffer,
  35168. resolveDepthBuffer: false,
  35169. resolveStencilBuffer: false
  35170. } );
  35171. layer.renderTarget.isXRRenderTarget = false;
  35172. layer.plane.material = layer.material;
  35173. layer.material.map = layer.renderTarget.texture;
  35174. delete layer.xrlayer;
  35175. }
  35176. }
  35177. //
  35178. this.isPresenting = false;
  35179. renderer._animation.stop();
  35180. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  35181. renderer._animation.setContext( this._currentAnimationContext );
  35182. renderer._animation.start();
  35183. renderer.setPixelRatio( this._currentPixelRatio );
  35184. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  35185. this.dispatchEvent( { type: 'sessionend' } );
  35186. }
  35187. function onInputSourcesChange( event ) {
  35188. const controllers = this._controllers;
  35189. const controllerInputSources = this._controllerInputSources;
  35190. // Notify disconnected
  35191. for ( let i = 0; i < event.removed.length; i ++ ) {
  35192. const inputSource = event.removed[ i ];
  35193. const index = controllerInputSources.indexOf( inputSource );
  35194. if ( index >= 0 ) {
  35195. controllerInputSources[ index ] = null;
  35196. controllers[ index ].disconnect( inputSource );
  35197. }
  35198. }
  35199. // Notify connected
  35200. for ( let i = 0; i < event.added.length; i ++ ) {
  35201. const inputSource = event.added[ i ];
  35202. let controllerIndex = controllerInputSources.indexOf( inputSource );
  35203. if ( controllerIndex === -1 ) {
  35204. // Assign input source a controller that currently has no input source
  35205. for ( let i = 0; i < controllers.length; i ++ ) {
  35206. if ( i >= controllerInputSources.length ) {
  35207. controllerInputSources.push( inputSource );
  35208. controllerIndex = i;
  35209. break;
  35210. } else if ( controllerInputSources[ i ] === null ) {
  35211. controllerInputSources[ i ] = inputSource;
  35212. controllerIndex = i;
  35213. break;
  35214. }
  35215. }
  35216. // If all controllers do currently receive input we ignore new ones
  35217. if ( controllerIndex === -1 ) break;
  35218. }
  35219. const controller = controllers[ controllerIndex ];
  35220. if ( controller ) {
  35221. controller.connect( inputSource );
  35222. }
  35223. }
  35224. }
  35225. // Creation method for native WebXR layers
  35226. function createXRLayer( layer ) {
  35227. if ( layer.type === 'quad' ) {
  35228. return this._glBinding.createQuadLayer( {
  35229. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  35230. depthFormat: this._gl.DEPTH_COMPONENT,
  35231. width: layer.width / 2,
  35232. height: layer.height / 2,
  35233. space: this._referenceSpace,
  35234. viewPixelWidth: layer.pixelwidth,
  35235. viewPixelHeight: layer.pixelheight
  35236. } );
  35237. } else {
  35238. return this._glBinding.createCylinderLayer( {
  35239. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  35240. depthFormat: this._gl.DEPTH_COMPONENT,
  35241. radius: layer.radius,
  35242. centralAngle: layer.centralAngle,
  35243. aspectRatio: layer.aspectRatio,
  35244. space: this._referenceSpace,
  35245. viewPixelWidth: layer.pixelwidth,
  35246. viewPixelHeight: layer.pixelheight
  35247. } );
  35248. }
  35249. }
  35250. // Animation Loop
  35251. function onAnimationFrame( time, frame ) {
  35252. if ( frame === undefined ) return;
  35253. const cameraXR = this._cameraXR;
  35254. const renderer = this._renderer;
  35255. const backend = renderer.backend;
  35256. const glBaseLayer = this._glBaseLayer;
  35257. const referenceSpace = this.getReferenceSpace();
  35258. const pose = frame.getViewerPose( referenceSpace );
  35259. this._xrFrame = frame;
  35260. if ( pose !== null ) {
  35261. const views = pose.views;
  35262. if ( this._glBaseLayer !== null ) {
  35263. backend.setXRTarget( glBaseLayer.framebuffer );
  35264. }
  35265. let cameraXRNeedsUpdate = false;
  35266. // check if it's necessary to rebuild cameraXR's camera list
  35267. if ( views.length !== cameraXR.cameras.length ) {
  35268. cameraXR.cameras.length = 0;
  35269. cameraXRNeedsUpdate = true;
  35270. }
  35271. for ( let i = 0; i < views.length; i ++ ) {
  35272. const view = views[ i ];
  35273. let viewport;
  35274. if ( this._useLayers === true ) {
  35275. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  35276. viewport = glSubImage.viewport;
  35277. // For side-by-side projection, we only produce a single texture for both eyes.
  35278. if ( i === 0 ) {
  35279. backend.setXRRenderTargetTextures(
  35280. this._xrRenderTarget,
  35281. glSubImage.colorTexture,
  35282. this._glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture
  35283. );
  35284. }
  35285. } else {
  35286. viewport = glBaseLayer.getViewport( view );
  35287. }
  35288. let camera = this._cameras[ i ];
  35289. if ( camera === undefined ) {
  35290. camera = new PerspectiveCamera();
  35291. camera.layers.enable( i );
  35292. camera.viewport = new Vector4();
  35293. this._cameras[ i ] = camera;
  35294. }
  35295. camera.matrix.fromArray( view.transform.matrix );
  35296. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  35297. camera.projectionMatrix.fromArray( view.projectionMatrix );
  35298. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  35299. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  35300. if ( i === 0 ) {
  35301. cameraXR.matrix.copy( camera.matrix );
  35302. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  35303. }
  35304. if ( cameraXRNeedsUpdate === true ) {
  35305. cameraXR.cameras.push( camera );
  35306. }
  35307. }
  35308. renderer.setOutputRenderTarget( this._xrRenderTarget );
  35309. }
  35310. //
  35311. for ( let i = 0; i < this._controllers.length; i ++ ) {
  35312. const inputSource = this._controllerInputSources[ i ];
  35313. const controller = this._controllers[ i ];
  35314. if ( inputSource !== null && controller !== undefined ) {
  35315. controller.update( inputSource, frame, referenceSpace );
  35316. }
  35317. }
  35318. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  35319. if ( frame.detectedPlanes ) {
  35320. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  35321. }
  35322. this._xrFrame = null;
  35323. }
  35324. const _scene = /*@__PURE__*/ new Scene();
  35325. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  35326. const _screen = /*@__PURE__*/ new Vector4();
  35327. const _frustum = /*@__PURE__*/ new Frustum();
  35328. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  35329. const _vector4 = /*@__PURE__*/ new Vector4();
  35330. /**
  35331. * Base class for renderers.
  35332. */
  35333. class Renderer {
  35334. /**
  35335. * Renderer options.
  35336. *
  35337. * @typedef {Object} Renderer~Options
  35338. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  35339. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  35340. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  35341. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  35342. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  35343. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  35344. * to overwrite the default.
  35345. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  35346. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  35347. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  35348. */
  35349. /**
  35350. * Constructs a new renderer.
  35351. *
  35352. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  35353. * @param {Renderer~Options} [parameters] - The configuration parameter.
  35354. */
  35355. constructor( backend, parameters = {} ) {
  35356. /**
  35357. * This flag can be used for type testing.
  35358. *
  35359. * @type {boolean}
  35360. * @readonly
  35361. * @default true
  35362. */
  35363. this.isRenderer = true;
  35364. //
  35365. const {
  35366. logarithmicDepthBuffer = false,
  35367. alpha = true,
  35368. depth = true,
  35369. stencil = false,
  35370. antialias = false,
  35371. samples = 0,
  35372. getFallback = null,
  35373. colorBufferType = HalfFloatType
  35374. } = parameters;
  35375. /**
  35376. * A reference to the canvas element the renderer is drawing to.
  35377. * This value of this property will automatically be created by
  35378. * the renderer.
  35379. *
  35380. * @type {HTMLCanvasElement|OffscreenCanvas}
  35381. */
  35382. this.domElement = backend.getDomElement();
  35383. /**
  35384. * A reference to the current backend.
  35385. *
  35386. * @type {Backend}
  35387. */
  35388. this.backend = backend;
  35389. /**
  35390. * The number of MSAA samples.
  35391. *
  35392. * @type {number}
  35393. * @default 0
  35394. */
  35395. this.samples = samples || ( antialias === true ) ? 4 : 0;
  35396. /**
  35397. * Whether the renderer should automatically clear the current rendering target
  35398. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  35399. * or the current bound render target (custom framebuffer).
  35400. *
  35401. * @type {boolean}
  35402. * @default true
  35403. */
  35404. this.autoClear = true;
  35405. /**
  35406. * When `autoClear` is set to `true`, this property defines whether the renderer
  35407. * should clear the color buffer.
  35408. *
  35409. * @type {boolean}
  35410. * @default true
  35411. */
  35412. this.autoClearColor = true;
  35413. /**
  35414. * When `autoClear` is set to `true`, this property defines whether the renderer
  35415. * should clear the depth buffer.
  35416. *
  35417. * @type {boolean}
  35418. * @default true
  35419. */
  35420. this.autoClearDepth = true;
  35421. /**
  35422. * When `autoClear` is set to `true`, this property defines whether the renderer
  35423. * should clear the stencil buffer.
  35424. *
  35425. * @type {boolean}
  35426. * @default true
  35427. */
  35428. this.autoClearStencil = true;
  35429. /**
  35430. * Whether the default framebuffer should be transparent or opaque.
  35431. *
  35432. * @type {boolean}
  35433. * @default true
  35434. */
  35435. this.alpha = alpha;
  35436. /**
  35437. * Whether logarithmic depth buffer is enabled or not.
  35438. *
  35439. * @type {boolean}
  35440. * @default false
  35441. */
  35442. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  35443. /**
  35444. * Defines the output color space of the renderer.
  35445. *
  35446. * @type {string}
  35447. * @default SRGBColorSpace
  35448. */
  35449. this.outputColorSpace = SRGBColorSpace;
  35450. /**
  35451. * Defines the tone mapping of the renderer.
  35452. *
  35453. * @type {number}
  35454. * @default NoToneMapping
  35455. */
  35456. this.toneMapping = NoToneMapping;
  35457. /**
  35458. * Defines the tone mapping exposure.
  35459. *
  35460. * @type {number}
  35461. * @default 1
  35462. */
  35463. this.toneMappingExposure = 1.0;
  35464. /**
  35465. * Whether the renderer should sort its render lists or not.
  35466. *
  35467. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  35468. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  35469. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  35470. * e.g. manually determining each object's rendering order.
  35471. *
  35472. * @type {boolean}
  35473. * @default true
  35474. */
  35475. this.sortObjects = true;
  35476. /**
  35477. * Whether the default framebuffer should have a depth buffer or not.
  35478. *
  35479. * @type {boolean}
  35480. * @default true
  35481. */
  35482. this.depth = depth;
  35483. /**
  35484. * Whether the default framebuffer should have a stencil buffer or not.
  35485. *
  35486. * @type {boolean}
  35487. * @default false
  35488. */
  35489. this.stencil = stencil;
  35490. /**
  35491. * Holds a series of statistical information about the GPU memory
  35492. * and the rendering process. Useful for debugging and monitoring.
  35493. *
  35494. * @type {Info}
  35495. */
  35496. this.info = new Info();
  35497. this.nodes = {
  35498. modelViewMatrix: null,
  35499. modelNormalViewMatrix: null
  35500. };
  35501. /**
  35502. * The node library defines how certain library objects like materials, lights
  35503. * or tone mapping functions are mapped to node types. This is required since
  35504. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  35505. * be part of the scene graph, they are internally represented as nodes for
  35506. * further processing.
  35507. *
  35508. * @type {NodeLibrary}
  35509. */
  35510. this.library = new NodeLibrary();
  35511. /**
  35512. * A map-like data structure for managing lights.
  35513. *
  35514. * @type {Lighting}
  35515. */
  35516. this.lighting = new Lighting();
  35517. // internals
  35518. /**
  35519. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  35520. *
  35521. * @private
  35522. * @type {?Function}
  35523. */
  35524. this._getFallback = getFallback;
  35525. /**
  35526. * The renderer's pixel ratio.
  35527. *
  35528. * @private
  35529. * @type {number}
  35530. * @default 1
  35531. */
  35532. this._pixelRatio = 1;
  35533. /**
  35534. * The width of the renderer's default framebuffer in logical pixel unit.
  35535. *
  35536. * @private
  35537. * @type {number}
  35538. */
  35539. this._width = this.domElement.width;
  35540. /**
  35541. * The height of the renderer's default framebuffer in logical pixel unit.
  35542. *
  35543. * @private
  35544. * @type {number}
  35545. */
  35546. this._height = this.domElement.height;
  35547. /**
  35548. * The viewport of the renderer in logical pixel unit.
  35549. *
  35550. * @private
  35551. * @type {Vector4}
  35552. */
  35553. this._viewport = new Vector4( 0, 0, this._width, this._height );
  35554. /**
  35555. * The scissor rectangle of the renderer in logical pixel unit.
  35556. *
  35557. * @private
  35558. * @type {Vector4}
  35559. */
  35560. this._scissor = new Vector4( 0, 0, this._width, this._height );
  35561. /**
  35562. * Whether the scissor test should be enabled or not.
  35563. *
  35564. * @private
  35565. * @type {boolean}
  35566. */
  35567. this._scissorTest = false;
  35568. /**
  35569. * A reference to a renderer module for managing shader attributes.
  35570. *
  35571. * @private
  35572. * @type {?Attributes}
  35573. * @default null
  35574. */
  35575. this._attributes = null;
  35576. /**
  35577. * A reference to a renderer module for managing geometries.
  35578. *
  35579. * @private
  35580. * @type {?Geometries}
  35581. * @default null
  35582. */
  35583. this._geometries = null;
  35584. /**
  35585. * A reference to a renderer module for managing node related logic.
  35586. *
  35587. * @private
  35588. * @type {?Nodes}
  35589. * @default null
  35590. */
  35591. this._nodes = null;
  35592. /**
  35593. * A reference to a renderer module for managing the internal animation loop.
  35594. *
  35595. * @private
  35596. * @type {?Animation}
  35597. * @default null
  35598. */
  35599. this._animation = null;
  35600. /**
  35601. * A reference to a renderer module for managing shader program bindings.
  35602. *
  35603. * @private
  35604. * @type {?Bindings}
  35605. * @default null
  35606. */
  35607. this._bindings = null;
  35608. /**
  35609. * A reference to a renderer module for managing render objects.
  35610. *
  35611. * @private
  35612. * @type {?RenderObjects}
  35613. * @default null
  35614. */
  35615. this._objects = null;
  35616. /**
  35617. * A reference to a renderer module for managing render and compute pipelines.
  35618. *
  35619. * @private
  35620. * @type {?Pipelines}
  35621. * @default null
  35622. */
  35623. this._pipelines = null;
  35624. /**
  35625. * A reference to a renderer module for managing render bundles.
  35626. *
  35627. * @private
  35628. * @type {?RenderBundles}
  35629. * @default null
  35630. */
  35631. this._bundles = null;
  35632. /**
  35633. * A reference to a renderer module for managing render lists.
  35634. *
  35635. * @private
  35636. * @type {?RenderLists}
  35637. * @default null
  35638. */
  35639. this._renderLists = null;
  35640. /**
  35641. * A reference to a renderer module for managing render contexts.
  35642. *
  35643. * @private
  35644. * @type {?RenderContexts}
  35645. * @default null
  35646. */
  35647. this._renderContexts = null;
  35648. /**
  35649. * A reference to a renderer module for managing textures.
  35650. *
  35651. * @private
  35652. * @type {?Textures}
  35653. * @default null
  35654. */
  35655. this._textures = null;
  35656. /**
  35657. * A reference to a renderer module for backgrounds.
  35658. *
  35659. * @private
  35660. * @type {?Background}
  35661. * @default null
  35662. */
  35663. this._background = null;
  35664. /**
  35665. * This fullscreen quad is used for internal render passes
  35666. * like the tone mapping and color space output pass.
  35667. *
  35668. * @private
  35669. * @type {QuadMesh}
  35670. */
  35671. this._quad = new QuadMesh( new NodeMaterial() );
  35672. this._quad.material.name = 'Renderer_output';
  35673. /**
  35674. * A reference to the current render context.
  35675. *
  35676. * @private
  35677. * @type {?RenderContext}
  35678. * @default null
  35679. */
  35680. this._currentRenderContext = null;
  35681. /**
  35682. * A custom sort function for the opaque render list.
  35683. *
  35684. * @private
  35685. * @type {?Function}
  35686. * @default null
  35687. */
  35688. this._opaqueSort = null;
  35689. /**
  35690. * A custom sort function for the transparent render list.
  35691. *
  35692. * @private
  35693. * @type {?Function}
  35694. * @default null
  35695. */
  35696. this._transparentSort = null;
  35697. /**
  35698. * The framebuffer target.
  35699. *
  35700. * @private
  35701. * @type {?RenderTarget}
  35702. * @default null
  35703. */
  35704. this._frameBufferTarget = null;
  35705. const alphaClear = this.alpha === true ? 0 : 1;
  35706. /**
  35707. * The clear color value.
  35708. *
  35709. * @private
  35710. * @type {Color4}
  35711. */
  35712. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  35713. /**
  35714. * The clear depth value.
  35715. *
  35716. * @private
  35717. * @type {number}
  35718. * @default 1
  35719. */
  35720. this._clearDepth = 1;
  35721. /**
  35722. * The clear stencil value.
  35723. *
  35724. * @private
  35725. * @type {number}
  35726. * @default 0
  35727. */
  35728. this._clearStencil = 0;
  35729. /**
  35730. * The current render target.
  35731. *
  35732. * @private
  35733. * @type {?RenderTarget}
  35734. * @default null
  35735. */
  35736. this._renderTarget = null;
  35737. /**
  35738. * The active cube face.
  35739. *
  35740. * @private
  35741. * @type {number}
  35742. * @default 0
  35743. */
  35744. this._activeCubeFace = 0;
  35745. /**
  35746. * The active mipmap level.
  35747. *
  35748. * @private
  35749. * @type {number}
  35750. * @default 0
  35751. */
  35752. this._activeMipmapLevel = 0;
  35753. /**
  35754. * The current output render target.
  35755. *
  35756. * @private
  35757. * @type {?RenderTarget}
  35758. * @default null
  35759. */
  35760. this._outputRenderTarget = null;
  35761. /**
  35762. * The MRT setting.
  35763. *
  35764. * @private
  35765. * @type {?MRTNode}
  35766. * @default null
  35767. */
  35768. this._mrt = null;
  35769. /**
  35770. * This function defines how a render object is going
  35771. * to be rendered.
  35772. *
  35773. * @private
  35774. * @type {?Function}
  35775. * @default null
  35776. */
  35777. this._renderObjectFunction = null;
  35778. /**
  35779. * Used to keep track of the current render object function.
  35780. *
  35781. * @private
  35782. * @type {?Function}
  35783. * @default null
  35784. */
  35785. this._currentRenderObjectFunction = null;
  35786. /**
  35787. * Used to keep track of the current render bundle.
  35788. *
  35789. * @private
  35790. * @type {?RenderBundle}
  35791. * @default null
  35792. */
  35793. this._currentRenderBundle = null;
  35794. /**
  35795. * Next to `_renderObjectFunction()`, this function provides another hook
  35796. * for influencing the render process of a render object. It is meant for internal
  35797. * use and only relevant for `compileAsync()` right now. Instead of using
  35798. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  35799. * a different function might be used which performs no draw but just the node
  35800. * and pipeline updates.
  35801. *
  35802. * @private
  35803. * @type {?Function}
  35804. * @default null
  35805. */
  35806. this._handleObjectFunction = this._renderObjectDirect;
  35807. /**
  35808. * Indicates whether the device has been lost or not. In WebGL terms, the device
  35809. * lost is considered as a context lost. When this is set to `true`, rendering
  35810. * isn't possible anymore.
  35811. *
  35812. * @private
  35813. * @type {boolean}
  35814. * @default false
  35815. */
  35816. this._isDeviceLost = false;
  35817. /**
  35818. * A callback function that defines what should happen when a device/context lost occurs.
  35819. *
  35820. * @type {Function}
  35821. */
  35822. this.onDeviceLost = this._onDeviceLost;
  35823. /**
  35824. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  35825. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  35826. * This will reduce rendering quality though.
  35827. *
  35828. * @private
  35829. * @type {number}
  35830. * @default HalfFloatType
  35831. */
  35832. this._colorBufferType = colorBufferType;
  35833. /**
  35834. * Whether the renderer has been initialized or not.
  35835. *
  35836. * @private
  35837. * @type {boolean}
  35838. * @default false
  35839. */
  35840. this._initialized = false;
  35841. /**
  35842. * A reference to the promise which initializes the renderer.
  35843. *
  35844. * @private
  35845. * @type {?Promise<this>}
  35846. * @default null
  35847. */
  35848. this._initPromise = null;
  35849. /**
  35850. * An array of compilation promises which are used in `compileAsync()`.
  35851. *
  35852. * @private
  35853. * @type {?Array<Promise>}
  35854. * @default null
  35855. */
  35856. this._compilationPromises = null;
  35857. /**
  35858. * Whether the renderer should render transparent render objects or not.
  35859. *
  35860. * @type {boolean}
  35861. * @default true
  35862. */
  35863. this.transparent = true;
  35864. /**
  35865. * Whether the renderer should render opaque render objects or not.
  35866. *
  35867. * @type {boolean}
  35868. * @default true
  35869. */
  35870. this.opaque = true;
  35871. /**
  35872. * Shadow map configuration
  35873. * @typedef {Object} ShadowMapConfig
  35874. * @property {boolean} enabled - Whether to globally enable shadows or not.
  35875. * @property {number} type - The shadow map type.
  35876. */
  35877. /**
  35878. * The renderer's shadow configuration.
  35879. *
  35880. * @type {ShadowMapConfig}
  35881. */
  35882. this.shadowMap = {
  35883. enabled: false,
  35884. type: PCFShadowMap
  35885. };
  35886. /**
  35887. * XR configuration.
  35888. * @typedef {Object} XRConfig
  35889. * @property {boolean} enabled - Whether to globally enable XR or not.
  35890. */
  35891. /**
  35892. * The renderer's XR manager.
  35893. *
  35894. * @type {XRManager}
  35895. */
  35896. this.xr = new XRManager( this );
  35897. /**
  35898. * Debug configuration.
  35899. * @typedef {Object} DebugConfig
  35900. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  35901. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  35902. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  35903. */
  35904. /**
  35905. * The renderer's debug configuration.
  35906. *
  35907. * @type {DebugConfig}
  35908. */
  35909. this.debug = {
  35910. checkShaderErrors: true,
  35911. onShaderError: null,
  35912. getShaderAsync: async ( scene, camera, object ) => {
  35913. await this.compileAsync( scene, camera );
  35914. const renderList = this._renderLists.get( scene, camera );
  35915. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  35916. const material = scene.overrideMaterial || object.material;
  35917. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  35918. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  35919. return { fragmentShader, vertexShader };
  35920. }
  35921. };
  35922. }
  35923. /**
  35924. * Initializes the renderer so it is ready for usage.
  35925. *
  35926. * @async
  35927. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  35928. */
  35929. async init() {
  35930. if ( this._initialized ) {
  35931. throw new Error( 'Renderer: Backend has already been initialized.' );
  35932. }
  35933. if ( this._initPromise !== null ) {
  35934. return this._initPromise;
  35935. }
  35936. this._initPromise = new Promise( async ( resolve, reject ) => {
  35937. let backend = this.backend;
  35938. try {
  35939. await backend.init( this );
  35940. } catch ( error ) {
  35941. if ( this._getFallback !== null ) {
  35942. // try the fallback
  35943. try {
  35944. this.backend = backend = this._getFallback( error );
  35945. await backend.init( this );
  35946. } catch ( error ) {
  35947. reject( error );
  35948. return;
  35949. }
  35950. } else {
  35951. reject( error );
  35952. return;
  35953. }
  35954. }
  35955. this._nodes = new Nodes( this, backend );
  35956. this._animation = new Animation( this._nodes, this.info );
  35957. this._attributes = new Attributes( backend );
  35958. this._background = new Background( this, this._nodes );
  35959. this._geometries = new Geometries( this._attributes, this.info );
  35960. this._textures = new Textures( this, backend, this.info );
  35961. this._pipelines = new Pipelines( backend, this._nodes );
  35962. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  35963. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  35964. this._renderLists = new RenderLists( this.lighting );
  35965. this._bundles = new RenderBundles();
  35966. this._renderContexts = new RenderContexts();
  35967. //
  35968. this._animation.start();
  35969. this._initialized = true;
  35970. resolve( this );
  35971. } );
  35972. return this._initPromise;
  35973. }
  35974. /**
  35975. * The coordinate system of the renderer. The value of this property
  35976. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  35977. * `THREE.WebGPUCoordinateSystem`.
  35978. *
  35979. * @readonly
  35980. * @type {number}
  35981. */
  35982. get coordinateSystem() {
  35983. return this.backend.coordinateSystem;
  35984. }
  35985. /**
  35986. * Compiles all materials in the given scene. This can be useful to avoid a
  35987. * phenomenon which is called "shader compilation stutter", which occurs when
  35988. * rendering an object with a new shader for the first time.
  35989. *
  35990. * If you want to add a 3D object to an existing scene, use the third optional
  35991. * parameter for applying the target scene. Note that the (target) scene's lighting
  35992. * and environment must be configured before calling this method.
  35993. *
  35994. * @async
  35995. * @param {Object3D} scene - The scene or 3D object to precompile.
  35996. * @param {Camera} camera - The camera that is used to render the scene.
  35997. * @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.
  35998. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  35999. */
  36000. async compileAsync( scene, camera, targetScene = null ) {
  36001. if ( this._isDeviceLost === true ) return;
  36002. if ( this._initialized === false ) await this.init();
  36003. // preserve render tree
  36004. const nodeFrame = this._nodes.nodeFrame;
  36005. const previousRenderId = nodeFrame.renderId;
  36006. const previousRenderContext = this._currentRenderContext;
  36007. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  36008. const previousCompilationPromises = this._compilationPromises;
  36009. //
  36010. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  36011. if ( targetScene === null ) targetScene = scene;
  36012. const renderTarget = this._renderTarget;
  36013. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  36014. const activeMipmapLevel = this._activeMipmapLevel;
  36015. const compilationPromises = [];
  36016. this._currentRenderContext = renderContext;
  36017. this._currentRenderObjectFunction = this.renderObject;
  36018. this._handleObjectFunction = this._createObjectPipeline;
  36019. this._compilationPromises = compilationPromises;
  36020. nodeFrame.renderId ++;
  36021. //
  36022. nodeFrame.update();
  36023. //
  36024. renderContext.depth = this.depth;
  36025. renderContext.stencil = this.stencil;
  36026. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36027. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  36028. //
  36029. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36030. //
  36031. const renderList = this._renderLists.get( scene, camera );
  36032. renderList.begin();
  36033. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  36034. // include lights from target scene
  36035. if ( targetScene !== scene ) {
  36036. targetScene.traverseVisible( function ( object ) {
  36037. if ( object.isLight && object.layers.test( camera.layers ) ) {
  36038. renderList.pushLight( object );
  36039. }
  36040. } );
  36041. }
  36042. renderList.finish();
  36043. //
  36044. if ( renderTarget !== null ) {
  36045. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36046. const renderTargetData = this._textures.get( renderTarget );
  36047. renderContext.textures = renderTargetData.textures;
  36048. renderContext.depthTexture = renderTargetData.depthTexture;
  36049. } else {
  36050. renderContext.textures = null;
  36051. renderContext.depthTexture = null;
  36052. }
  36053. //
  36054. this._background.update( sceneRef, renderList, renderContext );
  36055. // process render lists
  36056. const opaqueObjects = renderList.opaque;
  36057. const transparentObjects = renderList.transparent;
  36058. const transparentDoublePassObjects = renderList.transparentDoublePass;
  36059. const lightsNode = renderList.lightsNode;
  36060. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36061. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  36062. // restore render tree
  36063. nodeFrame.renderId = previousRenderId;
  36064. this._currentRenderContext = previousRenderContext;
  36065. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36066. this._compilationPromises = previousCompilationPromises;
  36067. this._handleObjectFunction = this._renderObjectDirect;
  36068. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  36069. await Promise.all( compilationPromises );
  36070. }
  36071. /**
  36072. * Renders the scene in an async fashion.
  36073. *
  36074. * @async
  36075. * @param {Object3D} scene - The scene or 3D object to render.
  36076. * @param {Camera} camera - The camera.
  36077. * @return {Promise} A Promise that resolves when the render has been finished.
  36078. */
  36079. async renderAsync( scene, camera ) {
  36080. if ( this._initialized === false ) await this.init();
  36081. this._renderScene( scene, camera );
  36082. }
  36083. /**
  36084. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  36085. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  36086. *
  36087. * @async
  36088. * @return {Promise} A Promise that resolves when synchronization has been finished.
  36089. */
  36090. async waitForGPU() {
  36091. await this.backend.waitForGPU();
  36092. }
  36093. /**
  36094. * Sets the given MRT configuration.
  36095. *
  36096. * @param {MRTNode} mrt - The MRT node to set.
  36097. * @return {Renderer} A reference to this renderer.
  36098. */
  36099. setMRT( mrt ) {
  36100. this._mrt = mrt;
  36101. return this;
  36102. }
  36103. /**
  36104. * Returns the MRT configuration.
  36105. *
  36106. * @return {MRTNode} The MRT configuration.
  36107. */
  36108. getMRT() {
  36109. return this._mrt;
  36110. }
  36111. /**
  36112. * Returns the color buffer type.
  36113. *
  36114. * @return {number} The color buffer type.
  36115. */
  36116. getColorBufferType() {
  36117. return this._colorBufferType;
  36118. }
  36119. /**
  36120. * Default implementation of the device lost callback.
  36121. *
  36122. * @private
  36123. * @param {Object} info - Information about the context lost.
  36124. */
  36125. _onDeviceLost( info ) {
  36126. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  36127. if ( info.reason ) {
  36128. errorMessage += `\nReason: ${info.reason}`;
  36129. }
  36130. console.error( errorMessage );
  36131. this._isDeviceLost = true;
  36132. }
  36133. /**
  36134. * Renders the given render bundle.
  36135. *
  36136. * @private
  36137. * @param {Object} bundle - Render bundle data.
  36138. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  36139. * @param {LightsNode} lightsNode - The lights node.
  36140. */
  36141. _renderBundle( bundle, sceneRef, lightsNode ) {
  36142. const { bundleGroup, camera, renderList } = bundle;
  36143. const renderContext = this._currentRenderContext;
  36144. //
  36145. const renderBundle = this._bundles.get( bundleGroup, camera );
  36146. const renderBundleData = this.backend.get( renderBundle );
  36147. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  36148. //
  36149. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  36150. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  36151. renderBundleData.renderContexts.add( renderContext );
  36152. if ( renderBundleNeedsUpdate ) {
  36153. this.backend.beginBundle( renderContext );
  36154. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  36155. renderBundleData.renderObjects = [];
  36156. }
  36157. this._currentRenderBundle = renderBundle;
  36158. const {
  36159. transparentDoublePass: transparentDoublePassObjects,
  36160. transparent: transparentObjects,
  36161. opaque: opaqueObjects
  36162. } = renderList;
  36163. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36164. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  36165. this._currentRenderBundle = null;
  36166. //
  36167. this.backend.finishBundle( renderContext, renderBundle );
  36168. renderBundleData.version = bundleGroup.version;
  36169. } else {
  36170. const { renderObjects } = renderBundleData;
  36171. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  36172. const renderObject = renderObjects[ i ];
  36173. if ( this._nodes.needsRefresh( renderObject ) ) {
  36174. this._nodes.updateBefore( renderObject );
  36175. this._nodes.updateForRender( renderObject );
  36176. this._bindings.updateForRender( renderObject );
  36177. this._nodes.updateAfter( renderObject );
  36178. }
  36179. }
  36180. }
  36181. this.backend.addBundle( renderContext, renderBundle );
  36182. }
  36183. /**
  36184. * Renders the scene or 3D object with the given camera. This method can only be called
  36185. * if the renderer has been initialized.
  36186. *
  36187. * The target of the method is the default framebuffer (meaning the canvas)
  36188. * or alternatively a render target when specified via `setRenderTarget()`.
  36189. *
  36190. * @param {Object3D} scene - The scene or 3D object to render.
  36191. * @param {Camera} camera - The camera to render the scene with.
  36192. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  36193. * Only returned when the renderer has not been initialized.
  36194. */
  36195. render( scene, camera ) {
  36196. if ( this._initialized === false ) {
  36197. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  36198. return this.renderAsync( scene, camera );
  36199. }
  36200. this._renderScene( scene, camera );
  36201. }
  36202. /**
  36203. * Returns an internal render target which is used when computing the output tone mapping
  36204. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  36205. * pass and not inline to achieve more correct results.
  36206. *
  36207. * @private
  36208. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  36209. */
  36210. _getFrameBufferTarget() {
  36211. const { currentToneMapping, currentColorSpace } = this;
  36212. const useToneMapping = currentToneMapping !== NoToneMapping;
  36213. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  36214. if ( useToneMapping === false && useColorSpace === false ) return null;
  36215. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  36216. const { depth, stencil } = this;
  36217. let frameBufferTarget = this._frameBufferTarget;
  36218. if ( frameBufferTarget === null ) {
  36219. frameBufferTarget = new RenderTarget( width, height, {
  36220. depthBuffer: depth,
  36221. stencilBuffer: stencil,
  36222. type: this._colorBufferType,
  36223. format: RGBAFormat,
  36224. colorSpace: LinearSRGBColorSpace,
  36225. generateMipmaps: false,
  36226. minFilter: LinearFilter,
  36227. magFilter: LinearFilter,
  36228. samples: this.samples
  36229. } );
  36230. frameBufferTarget.isPostProcessingRenderTarget = true;
  36231. this._frameBufferTarget = frameBufferTarget;
  36232. }
  36233. frameBufferTarget.depthBuffer = depth;
  36234. frameBufferTarget.stencilBuffer = stencil;
  36235. frameBufferTarget.setSize( width, height );
  36236. frameBufferTarget.viewport.copy( this._viewport );
  36237. frameBufferTarget.scissor.copy( this._scissor );
  36238. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  36239. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  36240. frameBufferTarget.scissorTest = this._scissorTest;
  36241. return frameBufferTarget;
  36242. }
  36243. /**
  36244. * Renders the scene or 3D object with the given camera.
  36245. *
  36246. * @private
  36247. * @param {Object3D} scene - The scene or 3D object to render.
  36248. * @param {Camera} camera - The camera to render the scene with.
  36249. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  36250. * @return {RenderContext} The current render context.
  36251. */
  36252. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  36253. if ( this._isDeviceLost === true ) return;
  36254. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  36255. // preserve render tree
  36256. const nodeFrame = this._nodes.nodeFrame;
  36257. const previousRenderId = nodeFrame.renderId;
  36258. const previousRenderContext = this._currentRenderContext;
  36259. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  36260. //
  36261. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  36262. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  36263. const activeCubeFace = this._activeCubeFace;
  36264. const activeMipmapLevel = this._activeMipmapLevel;
  36265. //
  36266. let renderTarget;
  36267. if ( frameBufferTarget !== null ) {
  36268. renderTarget = frameBufferTarget;
  36269. this.setRenderTarget( renderTarget );
  36270. } else {
  36271. renderTarget = outputRenderTarget;
  36272. }
  36273. //
  36274. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  36275. this._currentRenderContext = renderContext;
  36276. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  36277. //
  36278. this.info.calls ++;
  36279. this.info.render.calls ++;
  36280. this.info.render.frameCalls ++;
  36281. nodeFrame.renderId = this.info.calls;
  36282. //
  36283. const coordinateSystem = this.coordinateSystem;
  36284. const xr = this.xr;
  36285. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  36286. camera.coordinateSystem = coordinateSystem;
  36287. camera.updateProjectionMatrix();
  36288. if ( camera.isArrayCamera ) {
  36289. for ( const subCamera of camera.cameras ) {
  36290. subCamera.coordinateSystem = coordinateSystem;
  36291. subCamera.updateProjectionMatrix();
  36292. }
  36293. }
  36294. }
  36295. //
  36296. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  36297. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  36298. if ( xr.enabled === true && xr.isPresenting === true ) {
  36299. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  36300. camera = xr.getCamera(); // use XR camera for rendering
  36301. }
  36302. //
  36303. let viewport = this._viewport;
  36304. let scissor = this._scissor;
  36305. let pixelRatio = this._pixelRatio;
  36306. if ( renderTarget !== null ) {
  36307. viewport = renderTarget.viewport;
  36308. scissor = renderTarget.scissor;
  36309. pixelRatio = 1;
  36310. }
  36311. this.getDrawingBufferSize( _drawingBufferSize );
  36312. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  36313. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  36314. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  36315. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  36316. renderContext.viewportValue.width >>= activeMipmapLevel;
  36317. renderContext.viewportValue.height >>= activeMipmapLevel;
  36318. renderContext.viewportValue.minDepth = minDepth;
  36319. renderContext.viewportValue.maxDepth = maxDepth;
  36320. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  36321. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  36322. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  36323. renderContext.scissorValue.width >>= activeMipmapLevel;
  36324. renderContext.scissorValue.height >>= activeMipmapLevel;
  36325. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36326. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  36327. //
  36328. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36329. //
  36330. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  36331. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  36332. const renderList = this._renderLists.get( scene, camera );
  36333. renderList.begin();
  36334. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  36335. renderList.finish();
  36336. if ( this.sortObjects === true ) {
  36337. renderList.sort( this._opaqueSort, this._transparentSort );
  36338. }
  36339. //
  36340. if ( renderTarget !== null ) {
  36341. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36342. const renderTargetData = this._textures.get( renderTarget );
  36343. renderContext.textures = renderTargetData.textures;
  36344. renderContext.depthTexture = renderTargetData.depthTexture;
  36345. renderContext.width = renderTargetData.width;
  36346. renderContext.height = renderTargetData.height;
  36347. renderContext.renderTarget = renderTarget;
  36348. renderContext.depth = renderTarget.depthBuffer;
  36349. renderContext.stencil = renderTarget.stencilBuffer;
  36350. } else {
  36351. renderContext.textures = null;
  36352. renderContext.depthTexture = null;
  36353. renderContext.width = this.domElement.width;
  36354. renderContext.height = this.domElement.height;
  36355. renderContext.depth = this.depth;
  36356. renderContext.stencil = this.stencil;
  36357. }
  36358. renderContext.width >>= activeMipmapLevel;
  36359. renderContext.height >>= activeMipmapLevel;
  36360. renderContext.activeCubeFace = activeCubeFace;
  36361. renderContext.activeMipmapLevel = activeMipmapLevel;
  36362. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  36363. //
  36364. this._background.update( sceneRef, renderList, renderContext );
  36365. //
  36366. this.backend.beginRender( renderContext );
  36367. // process render lists
  36368. const {
  36369. bundles,
  36370. lightsNode,
  36371. transparentDoublePass: transparentDoublePassObjects,
  36372. transparent: transparentObjects,
  36373. opaque: opaqueObjects
  36374. } = renderList;
  36375. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  36376. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36377. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  36378. // finish render pass
  36379. this.backend.finishRender( renderContext );
  36380. // restore render tree
  36381. nodeFrame.renderId = previousRenderId;
  36382. this._currentRenderContext = previousRenderContext;
  36383. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36384. //
  36385. if ( frameBufferTarget !== null ) {
  36386. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  36387. this._renderOutput( renderTarget );
  36388. }
  36389. //
  36390. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  36391. //
  36392. return renderContext;
  36393. }
  36394. /**
  36395. * The output pass performs tone mapping and color space conversion.
  36396. *
  36397. * @private
  36398. * @param {RenderTarget} renderTarget - The current render target.
  36399. */
  36400. _renderOutput( renderTarget ) {
  36401. const quad = this._quad;
  36402. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  36403. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  36404. quad.material.needsUpdate = true;
  36405. }
  36406. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  36407. const currentAutoClear = this.autoClear;
  36408. const currentXR = this.xr.enabled;
  36409. this.autoClear = false;
  36410. this.xr.enabled = false;
  36411. this._renderScene( quad, quad.camera, false );
  36412. this.autoClear = currentAutoClear;
  36413. this.xr.enabled = currentXR;
  36414. }
  36415. /**
  36416. * Returns the maximum available anisotropy for texture filtering.
  36417. *
  36418. * @return {number} The maximum available anisotropy.
  36419. */
  36420. getMaxAnisotropy() {
  36421. return this.backend.getMaxAnisotropy();
  36422. }
  36423. /**
  36424. * Returns the active cube face.
  36425. *
  36426. * @return {number} The active cube face.
  36427. */
  36428. getActiveCubeFace() {
  36429. return this._activeCubeFace;
  36430. }
  36431. /**
  36432. * Returns the active mipmap level.
  36433. *
  36434. * @return {number} The active mipmap level.
  36435. */
  36436. getActiveMipmapLevel() {
  36437. return this._activeMipmapLevel;
  36438. }
  36439. /**
  36440. * Applications are advised to always define the animation loop
  36441. * with this method and not manually with `requestAnimationFrame()`
  36442. * for best compatibility.
  36443. *
  36444. * @async
  36445. * @param {?Function} callback - The application's animation loop.
  36446. * @return {Promise} A Promise that resolves when the set has been executed.
  36447. */
  36448. async setAnimationLoop( callback ) {
  36449. if ( this._initialized === false ) await this.init();
  36450. this._animation.setAnimationLoop( callback );
  36451. }
  36452. /**
  36453. * Can be used to transfer buffer data from a storage buffer attribute
  36454. * from the GPU to the CPU in context of compute shaders.
  36455. *
  36456. * @async
  36457. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  36458. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  36459. */
  36460. async getArrayBufferAsync( attribute ) {
  36461. return await this.backend.getArrayBufferAsync( attribute );
  36462. }
  36463. /**
  36464. * Returns the rendering context.
  36465. *
  36466. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  36467. */
  36468. getContext() {
  36469. return this.backend.getContext();
  36470. }
  36471. /**
  36472. * Returns the pixel ratio.
  36473. *
  36474. * @return {number} The pixel ratio.
  36475. */
  36476. getPixelRatio() {
  36477. return this._pixelRatio;
  36478. }
  36479. /**
  36480. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  36481. *
  36482. * @param {Vector2} target - The method writes the result in this target object.
  36483. * @return {Vector2} The drawing buffer size.
  36484. */
  36485. getDrawingBufferSize( target ) {
  36486. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  36487. }
  36488. /**
  36489. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  36490. *
  36491. * @param {Vector2} target - The method writes the result in this target object.
  36492. * @return {Vector2} The renderer's size in logical pixels.
  36493. */
  36494. getSize( target ) {
  36495. return target.set( this._width, this._height );
  36496. }
  36497. /**
  36498. * Sets the given pixel ratio and resizes the canvas if necessary.
  36499. *
  36500. * @param {number} [value=1] - The pixel ratio.
  36501. */
  36502. setPixelRatio( value = 1 ) {
  36503. if ( this._pixelRatio === value ) return;
  36504. this._pixelRatio = value;
  36505. this.setSize( this._width, this._height, false );
  36506. }
  36507. /**
  36508. * This method allows to define the drawing buffer size by specifying
  36509. * width, height and pixel ratio all at once. The size of the drawing
  36510. * buffer is computed with this formula:
  36511. * ```js
  36512. * size.x = width * pixelRatio;
  36513. * size.y = height * pixelRatio;
  36514. * ```
  36515. *
  36516. * @param {number} width - The width in logical pixels.
  36517. * @param {number} height - The height in logical pixels.
  36518. * @param {number} pixelRatio - The pixel ratio.
  36519. */
  36520. setDrawingBufferSize( width, height, pixelRatio ) {
  36521. // Renderer can't be resized while presenting in XR.
  36522. if ( this.xr && this.xr.isPresenting ) return;
  36523. this._width = width;
  36524. this._height = height;
  36525. this._pixelRatio = pixelRatio;
  36526. this.domElement.width = Math.floor( width * pixelRatio );
  36527. this.domElement.height = Math.floor( height * pixelRatio );
  36528. this.setViewport( 0, 0, width, height );
  36529. if ( this._initialized ) this.backend.updateSize();
  36530. }
  36531. /**
  36532. * Sets the size of the renderer.
  36533. *
  36534. * @param {number} width - The width in logical pixels.
  36535. * @param {number} height - The height in logical pixels.
  36536. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  36537. */
  36538. setSize( width, height, updateStyle = true ) {
  36539. // Renderer can't be resized while presenting in XR.
  36540. if ( this.xr && this.xr.isPresenting ) return;
  36541. this._width = width;
  36542. this._height = height;
  36543. this.domElement.width = Math.floor( width * this._pixelRatio );
  36544. this.domElement.height = Math.floor( height * this._pixelRatio );
  36545. if ( updateStyle === true ) {
  36546. this.domElement.style.width = width + 'px';
  36547. this.domElement.style.height = height + 'px';
  36548. }
  36549. this.setViewport( 0, 0, width, height );
  36550. if ( this._initialized ) this.backend.updateSize();
  36551. }
  36552. /**
  36553. * Defines a manual sort function for the opaque render list.
  36554. * Pass `null` to use the default sort.
  36555. *
  36556. * @param {Function} method - The sort function.
  36557. */
  36558. setOpaqueSort( method ) {
  36559. this._opaqueSort = method;
  36560. }
  36561. /**
  36562. * Defines a manual sort function for the transparent render list.
  36563. * Pass `null` to use the default sort.
  36564. *
  36565. * @param {Function} method - The sort function.
  36566. */
  36567. setTransparentSort( method ) {
  36568. this._transparentSort = method;
  36569. }
  36570. /**
  36571. * Returns the scissor rectangle.
  36572. *
  36573. * @param {Vector4} target - The method writes the result in this target object.
  36574. * @return {Vector4} The scissor rectangle.
  36575. */
  36576. getScissor( target ) {
  36577. const scissor = this._scissor;
  36578. target.x = scissor.x;
  36579. target.y = scissor.y;
  36580. target.width = scissor.width;
  36581. target.height = scissor.height;
  36582. return target;
  36583. }
  36584. /**
  36585. * Defines the scissor rectangle.
  36586. *
  36587. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  36588. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  36589. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  36590. * @param {number} width - The width of the scissor box in logical pixel unit.
  36591. * @param {number} height - The height of the scissor box in logical pixel unit.
  36592. */
  36593. setScissor( x, y, width, height ) {
  36594. const scissor = this._scissor;
  36595. if ( x.isVector4 ) {
  36596. scissor.copy( x );
  36597. } else {
  36598. scissor.set( x, y, width, height );
  36599. }
  36600. }
  36601. /**
  36602. * Returns the scissor test value.
  36603. *
  36604. * @return {boolean} Whether the scissor test should be enabled or not.
  36605. */
  36606. getScissorTest() {
  36607. return this._scissorTest;
  36608. }
  36609. /**
  36610. * Defines the scissor test.
  36611. *
  36612. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  36613. */
  36614. setScissorTest( boolean ) {
  36615. this._scissorTest = boolean;
  36616. this.backend.setScissorTest( boolean );
  36617. }
  36618. /**
  36619. * Returns the viewport definition.
  36620. *
  36621. * @param {Vector4} target - The method writes the result in this target object.
  36622. * @return {Vector4} The viewport definition.
  36623. */
  36624. getViewport( target ) {
  36625. return target.copy( this._viewport );
  36626. }
  36627. /**
  36628. * Defines the viewport.
  36629. *
  36630. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  36631. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  36632. * @param {number} width - The width of the viewport in logical pixel unit.
  36633. * @param {number} height - The height of the viewport in logical pixel unit.
  36634. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  36635. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  36636. */
  36637. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  36638. const viewport = this._viewport;
  36639. if ( x.isVector4 ) {
  36640. viewport.copy( x );
  36641. } else {
  36642. viewport.set( x, y, width, height );
  36643. }
  36644. viewport.minDepth = minDepth;
  36645. viewport.maxDepth = maxDepth;
  36646. }
  36647. /**
  36648. * Returns the clear color.
  36649. *
  36650. * @param {Color} target - The method writes the result in this target object.
  36651. * @return {Color} The clear color.
  36652. */
  36653. getClearColor( target ) {
  36654. return target.copy( this._clearColor );
  36655. }
  36656. /**
  36657. * Defines the clear color and optionally the clear alpha.
  36658. *
  36659. * @param {Color} color - The clear color.
  36660. * @param {number} [alpha=1] - The clear alpha.
  36661. */
  36662. setClearColor( color, alpha = 1 ) {
  36663. this._clearColor.set( color );
  36664. this._clearColor.a = alpha;
  36665. }
  36666. /**
  36667. * Returns the clear alpha.
  36668. *
  36669. * @return {number} The clear alpha.
  36670. */
  36671. getClearAlpha() {
  36672. return this._clearColor.a;
  36673. }
  36674. /**
  36675. * Defines the clear alpha.
  36676. *
  36677. * @param {number} alpha - The clear alpha.
  36678. */
  36679. setClearAlpha( alpha ) {
  36680. this._clearColor.a = alpha;
  36681. }
  36682. /**
  36683. * Returns the clear depth.
  36684. *
  36685. * @return {number} The clear depth.
  36686. */
  36687. getClearDepth() {
  36688. return this._clearDepth;
  36689. }
  36690. /**
  36691. * Defines the clear depth.
  36692. *
  36693. * @param {number} depth - The clear depth.
  36694. */
  36695. setClearDepth( depth ) {
  36696. this._clearDepth = depth;
  36697. }
  36698. /**
  36699. * Returns the clear stencil.
  36700. *
  36701. * @return {number} The clear stencil.
  36702. */
  36703. getClearStencil() {
  36704. return this._clearStencil;
  36705. }
  36706. /**
  36707. * Defines the clear stencil.
  36708. *
  36709. * @param {number} stencil - The clear stencil.
  36710. */
  36711. setClearStencil( stencil ) {
  36712. this._clearStencil = stencil;
  36713. }
  36714. /**
  36715. * This method performs an occlusion query for the given 3D object.
  36716. * It returns `true` if the given 3D object is fully occluded by other
  36717. * 3D objects in the scene.
  36718. *
  36719. * @param {Object3D} object - The 3D object to test.
  36720. * @return {boolean} Whether the 3D object is fully occluded or not.
  36721. */
  36722. isOccluded( object ) {
  36723. const renderContext = this._currentRenderContext;
  36724. return renderContext && this.backend.isOccluded( renderContext, object );
  36725. }
  36726. /**
  36727. * Performs a manual clear operation. This method ignores `autoClear` properties.
  36728. *
  36729. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  36730. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  36731. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  36732. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36733. * Only returned when the renderer has not been initialized.
  36734. */
  36735. clear( color = true, depth = true, stencil = true ) {
  36736. if ( this._initialized === false ) {
  36737. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  36738. return this.clearAsync( color, depth, stencil );
  36739. }
  36740. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  36741. let renderContext = null;
  36742. if ( renderTarget !== null ) {
  36743. this._textures.updateRenderTarget( renderTarget );
  36744. const renderTargetData = this._textures.get( renderTarget );
  36745. renderContext = this._renderContexts.getForClear( renderTarget );
  36746. renderContext.textures = renderTargetData.textures;
  36747. renderContext.depthTexture = renderTargetData.depthTexture;
  36748. renderContext.width = renderTargetData.width;
  36749. renderContext.height = renderTargetData.height;
  36750. renderContext.renderTarget = renderTarget;
  36751. renderContext.depth = renderTarget.depthBuffer;
  36752. renderContext.stencil = renderTarget.stencilBuffer;
  36753. // #30329
  36754. renderContext.clearColorValue = this.backend.getClearColor();
  36755. renderContext.activeCubeFace = this.getActiveCubeFace();
  36756. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  36757. }
  36758. this.backend.clear( color, depth, stencil, renderContext );
  36759. if ( renderTarget !== null && this._renderTarget === null ) {
  36760. this._renderOutput( renderTarget );
  36761. }
  36762. }
  36763. /**
  36764. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  36765. *
  36766. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36767. * Only returned when the renderer has not been initialized.
  36768. */
  36769. clearColor() {
  36770. return this.clear( true, false, false );
  36771. }
  36772. /**
  36773. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  36774. *
  36775. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36776. * Only returned when the renderer has not been initialized.
  36777. */
  36778. clearDepth() {
  36779. return this.clear( false, true, false );
  36780. }
  36781. /**
  36782. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  36783. *
  36784. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36785. * Only returned when the renderer has not been initialized.
  36786. */
  36787. clearStencil() {
  36788. return this.clear( false, false, true );
  36789. }
  36790. /**
  36791. * Async version of {@link Renderer#clear}.
  36792. *
  36793. * @async
  36794. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  36795. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  36796. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  36797. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36798. */
  36799. async clearAsync( color = true, depth = true, stencil = true ) {
  36800. if ( this._initialized === false ) await this.init();
  36801. this.clear( color, depth, stencil );
  36802. }
  36803. /**
  36804. * Async version of {@link Renderer#clearColor}.
  36805. *
  36806. * @async
  36807. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36808. */
  36809. async clearColorAsync() {
  36810. this.clearAsync( true, false, false );
  36811. }
  36812. /**
  36813. * Async version of {@link Renderer#clearDepth}.
  36814. *
  36815. * @async
  36816. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36817. */
  36818. async clearDepthAsync() {
  36819. this.clearAsync( false, true, false );
  36820. }
  36821. /**
  36822. * Async version of {@link Renderer#clearStencil}.
  36823. *
  36824. * @async
  36825. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  36826. */
  36827. async clearStencilAsync() {
  36828. this.clearAsync( false, false, true );
  36829. }
  36830. /**
  36831. * The current output tone mapping of the renderer. When a render target is set,
  36832. * the output tone mapping is always `NoToneMapping`.
  36833. *
  36834. * @type {number}
  36835. */
  36836. get currentToneMapping() {
  36837. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  36838. }
  36839. /**
  36840. * The current output color space of the renderer. When a render target is set,
  36841. * the output color space is always `LinearSRGBColorSpace`.
  36842. *
  36843. * @type {string}
  36844. */
  36845. get currentColorSpace() {
  36846. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  36847. }
  36848. /**
  36849. * Returns `true` if the rendering settings are set to screen output.
  36850. *
  36851. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  36852. */
  36853. get isOutputTarget() {
  36854. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  36855. }
  36856. /**
  36857. * Frees all internal resources of the renderer. Call this method if the renderer
  36858. * is no longer in use by your app.
  36859. */
  36860. dispose() {
  36861. this.info.dispose();
  36862. this.backend.dispose();
  36863. this._animation.dispose();
  36864. this._objects.dispose();
  36865. this._pipelines.dispose();
  36866. this._nodes.dispose();
  36867. this._bindings.dispose();
  36868. this._renderLists.dispose();
  36869. this._renderContexts.dispose();
  36870. this._textures.dispose();
  36871. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  36872. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  36873. if ( queryPool !== null ) queryPool.dispose();
  36874. } );
  36875. this.setRenderTarget( null );
  36876. this.setAnimationLoop( null );
  36877. }
  36878. /**
  36879. * Sets the given render target. Calling this method means the renderer does not
  36880. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  36881. * Use `null` as the first argument to reset the state.
  36882. *
  36883. * @param {?RenderTarget} renderTarget - The render target to set.
  36884. * @param {number} [activeCubeFace=0] - The active cube face.
  36885. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  36886. */
  36887. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  36888. this._renderTarget = renderTarget;
  36889. this._activeCubeFace = activeCubeFace;
  36890. this._activeMipmapLevel = activeMipmapLevel;
  36891. }
  36892. /**
  36893. * Returns the current render target.
  36894. *
  36895. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  36896. */
  36897. getRenderTarget() {
  36898. return this._renderTarget;
  36899. }
  36900. /**
  36901. * Sets the output render target for the renderer.
  36902. *
  36903. * @param {Object} renderTarget - The render target to set as the output target.
  36904. */
  36905. setOutputRenderTarget( renderTarget ) {
  36906. this._outputRenderTarget = renderTarget;
  36907. }
  36908. /**
  36909. * Returns the current output target.
  36910. *
  36911. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  36912. */
  36913. getOutputRenderTarget() {
  36914. return this._outputRenderTarget;
  36915. }
  36916. /**
  36917. * Callback for {@link Renderer#setRenderObjectFunction}.
  36918. *
  36919. * @callback renderObjectFunction
  36920. * @param {Object3D} object - The 3D object.
  36921. * @param {Scene} scene - The scene the 3D object belongs to.
  36922. * @param {Camera} camera - The camera the object should be rendered with.
  36923. * @param {BufferGeometry} geometry - The object's geometry.
  36924. * @param {Material} material - The object's material.
  36925. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  36926. * @param {LightsNode} lightsNode - The current lights node.
  36927. * @param {ClippingContext} clippingContext - The clipping context.
  36928. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  36929. */
  36930. /**
  36931. * Sets the given render object function. Calling this method overwrites the default implementation
  36932. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  36933. * if you want to modify the way objects are rendered. For example you can define things like "every
  36934. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  36935. * The custom function must always call `renderObject()` in its implementation.
  36936. *
  36937. * Use `null` as the first argument to reset the state.
  36938. *
  36939. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  36940. */
  36941. setRenderObjectFunction( renderObjectFunction ) {
  36942. this._renderObjectFunction = renderObjectFunction;
  36943. }
  36944. /**
  36945. * Returns the current render object function.
  36946. *
  36947. * @return {?Function} The current render object function. Returns `null` if no function is set.
  36948. */
  36949. getRenderObjectFunction() {
  36950. return this._renderObjectFunction;
  36951. }
  36952. /**
  36953. * Execute a single or an array of compute nodes. This method can only be called
  36954. * if the renderer has been initialized.
  36955. *
  36956. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  36957. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  36958. */
  36959. compute( computeNodes ) {
  36960. if ( this._isDeviceLost === true ) return;
  36961. if ( this._initialized === false ) {
  36962. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  36963. return this.computeAsync( computeNodes );
  36964. }
  36965. //
  36966. const nodeFrame = this._nodes.nodeFrame;
  36967. const previousRenderId = nodeFrame.renderId;
  36968. //
  36969. this.info.calls ++;
  36970. this.info.compute.calls ++;
  36971. this.info.compute.frameCalls ++;
  36972. nodeFrame.renderId = this.info.calls;
  36973. //
  36974. const backend = this.backend;
  36975. const pipelines = this._pipelines;
  36976. const bindings = this._bindings;
  36977. const nodes = this._nodes;
  36978. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  36979. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  36980. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  36981. }
  36982. backend.beginCompute( computeNodes );
  36983. for ( const computeNode of computeList ) {
  36984. // onInit
  36985. if ( pipelines.has( computeNode ) === false ) {
  36986. const dispose = () => {
  36987. computeNode.removeEventListener( 'dispose', dispose );
  36988. pipelines.delete( computeNode );
  36989. bindings.delete( computeNode );
  36990. nodes.delete( computeNode );
  36991. };
  36992. computeNode.addEventListener( 'dispose', dispose );
  36993. //
  36994. const onInitFn = computeNode.onInitFunction;
  36995. if ( onInitFn !== null ) {
  36996. onInitFn.call( computeNode, { renderer: this } );
  36997. }
  36998. }
  36999. nodes.updateForCompute( computeNode );
  37000. bindings.updateForCompute( computeNode );
  37001. const computeBindings = bindings.getForCompute( computeNode );
  37002. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  37003. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  37004. }
  37005. backend.finishCompute( computeNodes );
  37006. //
  37007. nodeFrame.renderId = previousRenderId;
  37008. }
  37009. /**
  37010. * Execute a single or an array of compute nodes.
  37011. *
  37012. * @async
  37013. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  37014. * @return {Promise} A Promise that resolve when the compute has finished.
  37015. */
  37016. async computeAsync( computeNodes ) {
  37017. if ( this._initialized === false ) await this.init();
  37018. this.compute( computeNodes );
  37019. }
  37020. /**
  37021. * Checks if the given feature is supported by the selected backend.
  37022. *
  37023. * @async
  37024. * @param {string} name - The feature's name.
  37025. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  37026. */
  37027. async hasFeatureAsync( name ) {
  37028. if ( this._initialized === false ) await this.init();
  37029. return this.backend.hasFeature( name );
  37030. }
  37031. async resolveTimestampsAsync( type = 'render' ) {
  37032. if ( this._initialized === false ) await this.init();
  37033. return this.backend.resolveTimestampsAsync( type );
  37034. }
  37035. /**
  37036. * Checks if the given feature is supported by the selected backend. If the
  37037. * renderer has not been initialized, this method always returns `false`.
  37038. *
  37039. * @param {string} name - The feature's name.
  37040. * @return {boolean} Whether the feature is supported or not.
  37041. */
  37042. hasFeature( name ) {
  37043. if ( this._initialized === false ) {
  37044. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  37045. return false;
  37046. }
  37047. return this.backend.hasFeature( name );
  37048. }
  37049. /**
  37050. * Returns `true` when the renderer has been initialized.
  37051. *
  37052. * @return {boolean} Whether the renderer has been initialized or not.
  37053. */
  37054. hasInitialized() {
  37055. return this._initialized;
  37056. }
  37057. /**
  37058. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  37059. * (which can cause noticeable lags due to decode and GPU upload overhead).
  37060. *
  37061. * @async
  37062. * @param {Texture} texture - The texture.
  37063. * @return {Promise} A Promise that resolves when the texture has been initialized.
  37064. */
  37065. async initTextureAsync( texture ) {
  37066. if ( this._initialized === false ) await this.init();
  37067. this._textures.updateTexture( texture );
  37068. }
  37069. /**
  37070. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  37071. * (which can cause noticeable lags due to decode and GPU upload overhead).
  37072. *
  37073. * This method can only be used if the renderer has been initialized.
  37074. *
  37075. * @param {Texture} texture - The texture.
  37076. */
  37077. initTexture( texture ) {
  37078. if ( this._initialized === false ) {
  37079. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  37080. }
  37081. this._textures.updateTexture( texture );
  37082. }
  37083. /**
  37084. * Copies the current bound framebuffer into the given texture.
  37085. *
  37086. * @param {FramebufferTexture} framebufferTexture - The texture.
  37087. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  37088. */
  37089. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  37090. if ( rectangle !== null ) {
  37091. if ( rectangle.isVector2 ) {
  37092. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  37093. } else if ( rectangle.isVector4 ) {
  37094. rectangle = _vector4.copy( rectangle ).floor();
  37095. } else {
  37096. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  37097. return;
  37098. }
  37099. } else {
  37100. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  37101. }
  37102. //
  37103. let renderContext = this._currentRenderContext;
  37104. let renderTarget;
  37105. if ( renderContext !== null ) {
  37106. renderTarget = renderContext.renderTarget;
  37107. } else {
  37108. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37109. if ( renderTarget !== null ) {
  37110. this._textures.updateRenderTarget( renderTarget );
  37111. renderContext = this._textures.get( renderTarget );
  37112. }
  37113. }
  37114. //
  37115. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  37116. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  37117. }
  37118. /**
  37119. * Copies data of the given source texture into a destination texture.
  37120. *
  37121. * @param {Texture} srcTexture - The source texture.
  37122. * @param {Texture} dstTexture - The destination texture.
  37123. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  37124. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  37125. * @param {number} [srcLevel=0] - The source mip level to copy from.
  37126. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  37127. */
  37128. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  37129. this._textures.updateTexture( srcTexture );
  37130. this._textures.updateTexture( dstTexture );
  37131. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  37132. }
  37133. /**
  37134. * Reads pixel data from the given render target.
  37135. *
  37136. * @async
  37137. * @param {RenderTarget} renderTarget - The render target to read from.
  37138. * @param {number} x - The `x` coordinate of the copy region's origin.
  37139. * @param {number} y - The `y` coordinate of the copy region's origin.
  37140. * @param {number} width - The width of the copy region.
  37141. * @param {number} height - The height of the copy region.
  37142. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  37143. * @param {number} [faceIndex=0] - The active cube face index.
  37144. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  37145. */
  37146. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  37147. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  37148. }
  37149. /**
  37150. * Analyzes the given 3D object's hierarchy and builds render lists from the
  37151. * processed hierarchy.
  37152. *
  37153. * @param {Object3D} object - The 3D object to process (usually a scene).
  37154. * @param {Camera} camera - The camera the object is rendered with.
  37155. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  37156. * @param {RenderList} renderList - The current render list.
  37157. * @param {ClippingContext} clippingContext - The current clipping context.
  37158. */
  37159. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  37160. if ( object.visible === false ) return;
  37161. const visible = object.layers.test( camera.layers );
  37162. if ( visible ) {
  37163. if ( object.isGroup ) {
  37164. groupOrder = object.renderOrder;
  37165. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  37166. } else if ( object.isLOD ) {
  37167. if ( object.autoUpdate === true ) object.update( camera );
  37168. } else if ( object.isLight ) {
  37169. renderList.pushLight( object );
  37170. } else if ( object.isSprite ) {
  37171. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  37172. if ( this.sortObjects === true ) {
  37173. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  37174. }
  37175. const { geometry, material } = object;
  37176. if ( material.visible ) {
  37177. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  37178. }
  37179. }
  37180. } else if ( object.isLineLoop ) {
  37181. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  37182. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  37183. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  37184. const { geometry, material } = object;
  37185. if ( this.sortObjects === true ) {
  37186. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  37187. _vector4
  37188. .copy( geometry.boundingSphere.center )
  37189. .applyMatrix4( object.matrixWorld )
  37190. .applyMatrix4( _projScreenMatrix );
  37191. }
  37192. if ( Array.isArray( material ) ) {
  37193. const groups = geometry.groups;
  37194. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  37195. const group = groups[ i ];
  37196. const groupMaterial = material[ group.materialIndex ];
  37197. if ( groupMaterial && groupMaterial.visible ) {
  37198. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  37199. }
  37200. }
  37201. } else if ( material.visible ) {
  37202. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  37203. }
  37204. }
  37205. }
  37206. }
  37207. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  37208. const baseRenderList = renderList;
  37209. // replace render list
  37210. renderList = this._renderLists.get( object, camera );
  37211. renderList.begin();
  37212. baseRenderList.pushBundle( {
  37213. bundleGroup: object,
  37214. camera,
  37215. renderList,
  37216. } );
  37217. renderList.finish();
  37218. }
  37219. const children = object.children;
  37220. for ( let i = 0, l = children.length; i < l; i ++ ) {
  37221. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  37222. }
  37223. }
  37224. /**
  37225. * Renders the given render bundles.
  37226. *
  37227. * @private
  37228. * @param {Array<Object>} bundles - Array with render bundle data.
  37229. * @param {Scene} sceneRef - The scene the render bundles belong to.
  37230. * @param {LightsNode} lightsNode - The current lights node.
  37231. */
  37232. _renderBundles( bundles, sceneRef, lightsNode ) {
  37233. for ( const bundle of bundles ) {
  37234. this._renderBundle( bundle, sceneRef, lightsNode );
  37235. }
  37236. }
  37237. /**
  37238. * Renders the transparent objects from the given render lists.
  37239. *
  37240. * @private
  37241. * @param {Array<Object>} renderList - The transparent render list.
  37242. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  37243. * @param {Camera} camera - The camera the render list should be rendered with.
  37244. * @param {Scene} scene - The scene the render list belongs to.
  37245. * @param {LightsNode} lightsNode - The current lights node.
  37246. */
  37247. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  37248. if ( doublePassList.length > 0 ) {
  37249. // render back side
  37250. for ( const { material } of doublePassList ) {
  37251. material.side = BackSide;
  37252. }
  37253. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  37254. // render front side
  37255. for ( const { material } of doublePassList ) {
  37256. material.side = FrontSide;
  37257. }
  37258. this._renderObjects( renderList, camera, scene, lightsNode );
  37259. // restore
  37260. for ( const { material } of doublePassList ) {
  37261. material.side = DoubleSide;
  37262. }
  37263. } else {
  37264. this._renderObjects( renderList, camera, scene, lightsNode );
  37265. }
  37266. }
  37267. /**
  37268. * Renders the objects from the given render list.
  37269. *
  37270. * @private
  37271. * @param {Array<Object>} renderList - The render list.
  37272. * @param {Camera} camera - The camera the render list should be rendered with.
  37273. * @param {Scene} scene - The scene the render list belongs to.
  37274. * @param {LightsNode} lightsNode - The current lights node.
  37275. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37276. */
  37277. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  37278. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  37279. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  37280. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  37281. }
  37282. }
  37283. /**
  37284. * This method represents the default render object function that manages the render lifecycle
  37285. * of the object.
  37286. *
  37287. * @param {Object3D} object - The 3D object.
  37288. * @param {Scene} scene - The scene the 3D object belongs to.
  37289. * @param {Camera} camera - The camera the object should be rendered with.
  37290. * @param {BufferGeometry} geometry - The object's geometry.
  37291. * @param {Material} material - The object's material.
  37292. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  37293. * @param {LightsNode} lightsNode - The current lights node.
  37294. * @param {?ClippingContext} clippingContext - The clipping context.
  37295. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37296. */
  37297. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  37298. let overridePositionNode;
  37299. let overrideColorNode;
  37300. let overrideDepthNode;
  37301. //
  37302. object.onBeforeRender( this, scene, camera, geometry, material, group );
  37303. //
  37304. if ( scene.overrideMaterial !== null ) {
  37305. const overrideMaterial = scene.overrideMaterial;
  37306. if ( material.positionNode && material.positionNode.isNode ) {
  37307. overridePositionNode = overrideMaterial.positionNode;
  37308. overrideMaterial.positionNode = material.positionNode;
  37309. }
  37310. overrideMaterial.alphaTest = material.alphaTest;
  37311. overrideMaterial.alphaMap = material.alphaMap;
  37312. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  37313. if ( overrideMaterial.isShadowPassMaterial ) {
  37314. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  37315. if ( material.depthNode && material.depthNode.isNode ) {
  37316. overrideDepthNode = overrideMaterial.depthNode;
  37317. overrideMaterial.depthNode = material.depthNode;
  37318. }
  37319. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  37320. overrideColorNode = overrideMaterial.colorNode;
  37321. overrideMaterial.colorNode = material.castShadowNode;
  37322. }
  37323. }
  37324. material = overrideMaterial;
  37325. }
  37326. //
  37327. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  37328. material.side = BackSide;
  37329. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  37330. material.side = FrontSide;
  37331. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  37332. material.side = DoubleSide;
  37333. } else {
  37334. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  37335. }
  37336. //
  37337. if ( overridePositionNode !== undefined ) {
  37338. scene.overrideMaterial.positionNode = overridePositionNode;
  37339. }
  37340. if ( overrideDepthNode !== undefined ) {
  37341. scene.overrideMaterial.depthNode = overrideDepthNode;
  37342. }
  37343. if ( overrideColorNode !== undefined ) {
  37344. scene.overrideMaterial.colorNode = overrideColorNode;
  37345. }
  37346. //
  37347. object.onAfterRender( this, scene, camera, geometry, material, group );
  37348. }
  37349. /**
  37350. * This method represents the default `_handleObjectFunction` implementation which creates
  37351. * a render object from the given data and performs the draw command with the selected backend.
  37352. *
  37353. * @private
  37354. * @param {Object3D} object - The 3D object.
  37355. * @param {Material} material - The object's material.
  37356. * @param {Scene} scene - The scene the 3D object belongs to.
  37357. * @param {Camera} camera - The camera the object should be rendered with.
  37358. * @param {LightsNode} lightsNode - The current lights node.
  37359. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  37360. * @param {ClippingContext} clippingContext - The clipping context.
  37361. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37362. */
  37363. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  37364. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  37365. renderObject.drawRange = object.geometry.drawRange;
  37366. renderObject.group = group;
  37367. //
  37368. const needsRefresh = this._nodes.needsRefresh( renderObject );
  37369. if ( needsRefresh ) {
  37370. this._nodes.updateBefore( renderObject );
  37371. this._geometries.updateForRender( renderObject );
  37372. this._nodes.updateForRender( renderObject );
  37373. this._bindings.updateForRender( renderObject );
  37374. }
  37375. this._pipelines.updateForRender( renderObject );
  37376. //
  37377. if ( this._currentRenderBundle !== null ) {
  37378. const renderBundleData = this.backend.get( this._currentRenderBundle );
  37379. renderBundleData.renderObjects.push( renderObject );
  37380. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  37381. }
  37382. this.backend.draw( renderObject, this.info );
  37383. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  37384. }
  37385. /**
  37386. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  37387. * Used in `compileAsync()`.
  37388. *
  37389. * @private
  37390. * @param {Object3D} object - The 3D object.
  37391. * @param {Material} material - The object's material.
  37392. * @param {Scene} scene - The scene the 3D object belongs to.
  37393. * @param {Camera} camera - The camera the object should be rendered with.
  37394. * @param {LightsNode} lightsNode - The current lights node.
  37395. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  37396. * @param {ClippingContext} clippingContext - The clipping context.
  37397. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37398. */
  37399. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  37400. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  37401. renderObject.drawRange = object.geometry.drawRange;
  37402. renderObject.group = group;
  37403. //
  37404. this._nodes.updateBefore( renderObject );
  37405. this._geometries.updateForRender( renderObject );
  37406. this._nodes.updateForRender( renderObject );
  37407. this._bindings.updateForRender( renderObject );
  37408. this._pipelines.getForRender( renderObject, this._compilationPromises );
  37409. this._nodes.updateAfter( renderObject );
  37410. }
  37411. /**
  37412. * Alias for `compileAsync()`.
  37413. *
  37414. * @method
  37415. * @param {Object3D} scene - The scene or 3D object to precompile.
  37416. * @param {Camera} camera - The camera that is used to render the scene.
  37417. * @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.
  37418. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  37419. */
  37420. get compile() {
  37421. return this.compileAsync;
  37422. }
  37423. }
  37424. /**
  37425. * A binding represents the connection between a resource (like a texture, sampler
  37426. * or uniform buffer) and the resource definition in a shader stage.
  37427. *
  37428. * This module is an abstract base class for all concrete bindings types.
  37429. *
  37430. * @abstract
  37431. * @private
  37432. */
  37433. class Binding {
  37434. /**
  37435. * Constructs a new binding.
  37436. *
  37437. * @param {string} [name=''] - The binding's name.
  37438. */
  37439. constructor( name = '' ) {
  37440. /**
  37441. * The binding's name.
  37442. *
  37443. * @type {string}
  37444. */
  37445. this.name = name;
  37446. /**
  37447. * A bitmask that defines in what shader stages the
  37448. * binding's resource is accessible.
  37449. *
  37450. * @type {number}
  37451. */
  37452. this.visibility = 0;
  37453. }
  37454. /**
  37455. * Makes sure binding's resource is visible for the given shader stage.
  37456. *
  37457. * @param {number} visibility - The shader stage.
  37458. */
  37459. setVisibility( visibility ) {
  37460. this.visibility |= visibility;
  37461. }
  37462. /**
  37463. * Clones the binding.
  37464. *
  37465. * @return {Binding} The cloned binding.
  37466. */
  37467. clone() {
  37468. return Object.assign( new this.constructor(), this );
  37469. }
  37470. }
  37471. /**
  37472. * This function is usually called with the length in bytes of an array buffer.
  37473. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  37474. *
  37475. * @function
  37476. * @param {number} floatLength - The buffer length.
  37477. * @return {number} The padded length.
  37478. */
  37479. function getFloatLength( floatLength ) {
  37480. // ensure chunk size alignment (STD140 layout)
  37481. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  37482. }
  37483. /**
  37484. * Represents a buffer binding type.
  37485. *
  37486. * @private
  37487. * @abstract
  37488. * @augments Binding
  37489. */
  37490. class Buffer extends Binding {
  37491. /**
  37492. * Constructs a new buffer.
  37493. *
  37494. * @param {string} name - The buffer's name.
  37495. * @param {TypedArray} [buffer=null] - The buffer.
  37496. */
  37497. constructor( name, buffer = null ) {
  37498. super( name );
  37499. /**
  37500. * This flag can be used for type testing.
  37501. *
  37502. * @type {boolean}
  37503. * @readonly
  37504. * @default true
  37505. */
  37506. this.isBuffer = true;
  37507. /**
  37508. * The bytes per element.
  37509. *
  37510. * @type {number}
  37511. */
  37512. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  37513. /**
  37514. * A reference to the internal buffer.
  37515. *
  37516. * @private
  37517. * @type {TypedArray}
  37518. */
  37519. this._buffer = buffer;
  37520. }
  37521. /**
  37522. * The buffer's byte length.
  37523. *
  37524. * @type {number}
  37525. * @readonly
  37526. */
  37527. get byteLength() {
  37528. return getFloatLength( this._buffer.byteLength );
  37529. }
  37530. /**
  37531. * A reference to the internal buffer.
  37532. *
  37533. * @type {Float32Array}
  37534. * @readonly
  37535. */
  37536. get buffer() {
  37537. return this._buffer;
  37538. }
  37539. /**
  37540. * Updates the binding.
  37541. *
  37542. * @return {boolean} Whether the buffer has been updated and must be
  37543. * uploaded to the GPU.
  37544. */
  37545. update() {
  37546. return true;
  37547. }
  37548. }
  37549. /**
  37550. * Represents a uniform buffer binding type.
  37551. *
  37552. * @private
  37553. * @augments Buffer
  37554. */
  37555. class UniformBuffer extends Buffer {
  37556. /**
  37557. * Constructs a new uniform buffer.
  37558. *
  37559. * @param {string} name - The buffer's name.
  37560. * @param {TypedArray} [buffer=null] - The buffer.
  37561. */
  37562. constructor( name, buffer = null ) {
  37563. super( name, buffer );
  37564. /**
  37565. * This flag can be used for type testing.
  37566. *
  37567. * @type {boolean}
  37568. * @readonly
  37569. * @default true
  37570. */
  37571. this.isUniformBuffer = true;
  37572. }
  37573. }
  37574. let _id$4 = 0;
  37575. /**
  37576. * A special form of uniform buffer binding type.
  37577. * It's buffer value is managed by a node object.
  37578. *
  37579. * @private
  37580. * @augments UniformBuffer
  37581. */
  37582. class NodeUniformBuffer extends UniformBuffer {
  37583. /**
  37584. * Constructs a new node-based uniform buffer.
  37585. *
  37586. * @param {BufferNode} nodeUniform - The uniform buffer node.
  37587. * @param {UniformGroupNode} groupNode - The uniform group node.
  37588. */
  37589. constructor( nodeUniform, groupNode ) {
  37590. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  37591. /**
  37592. * The uniform buffer node.
  37593. *
  37594. * @type {BufferNode}
  37595. */
  37596. this.nodeUniform = nodeUniform;
  37597. /**
  37598. * The uniform group node.
  37599. *
  37600. * @type {UniformGroupNode}
  37601. */
  37602. this.groupNode = groupNode;
  37603. }
  37604. /**
  37605. * The uniform buffer.
  37606. *
  37607. * @type {Float32Array}
  37608. */
  37609. get buffer() {
  37610. return this.nodeUniform.value;
  37611. }
  37612. }
  37613. /**
  37614. * This class represents a uniform buffer binding but with
  37615. * an API that allows to maintain individual uniform objects.
  37616. *
  37617. * @private
  37618. * @augments UniformBuffer
  37619. */
  37620. class UniformsGroup extends UniformBuffer {
  37621. /**
  37622. * Constructs a new uniforms group.
  37623. *
  37624. * @param {string} name - The group's name.
  37625. */
  37626. constructor( name ) {
  37627. super( name );
  37628. /**
  37629. * This flag can be used for type testing.
  37630. *
  37631. * @type {boolean}
  37632. * @readonly
  37633. * @default true
  37634. */
  37635. this.isUniformsGroup = true;
  37636. /**
  37637. * An array with the raw uniform values.
  37638. *
  37639. * @private
  37640. * @type {?Array<number>}
  37641. * @default null
  37642. */
  37643. this._values = null;
  37644. /**
  37645. * An array of uniform objects.
  37646. *
  37647. * The order of uniforms in this array must match the order of uniforms in the shader.
  37648. *
  37649. * @type {Array<Uniform>}
  37650. */
  37651. this.uniforms = [];
  37652. }
  37653. /**
  37654. * Adds a uniform to this group.
  37655. *
  37656. * @param {Uniform} uniform - The uniform to add.
  37657. * @return {UniformsGroup} A reference to this group.
  37658. */
  37659. addUniform( uniform ) {
  37660. this.uniforms.push( uniform );
  37661. return this;
  37662. }
  37663. /**
  37664. * Removes a uniform from this group.
  37665. *
  37666. * @param {Uniform} uniform - The uniform to remove.
  37667. * @return {UniformsGroup} A reference to this group.
  37668. */
  37669. removeUniform( uniform ) {
  37670. const index = this.uniforms.indexOf( uniform );
  37671. if ( index !== -1 ) {
  37672. this.uniforms.splice( index, 1 );
  37673. }
  37674. return this;
  37675. }
  37676. /**
  37677. * An array with the raw uniform values.
  37678. *
  37679. * @type {Array<number>}
  37680. */
  37681. get values() {
  37682. if ( this._values === null ) {
  37683. this._values = Array.from( this.buffer );
  37684. }
  37685. return this._values;
  37686. }
  37687. /**
  37688. * A Float32 array buffer with the uniform values.
  37689. *
  37690. * @type {Float32Array}
  37691. */
  37692. get buffer() {
  37693. let buffer = this._buffer;
  37694. if ( buffer === null ) {
  37695. const byteLength = this.byteLength;
  37696. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  37697. this._buffer = buffer;
  37698. }
  37699. return buffer;
  37700. }
  37701. /**
  37702. * The byte length of the buffer with correct buffer alignment.
  37703. *
  37704. * @type {number}
  37705. */
  37706. get byteLength() {
  37707. let offset = 0; // global buffer offset in bytes
  37708. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  37709. const uniform = this.uniforms[ i ];
  37710. const { boundary, itemSize } = uniform;
  37711. // offset within a single chunk in bytes
  37712. const chunkOffset = offset % GPU_CHUNK_BYTES;
  37713. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  37714. // conformance tests
  37715. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  37716. // check for chunk overflow
  37717. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  37718. } else if ( chunkOffset % boundary !== 0 ) {
  37719. // check for correct alignment
  37720. offset += ( chunkOffset % boundary );
  37721. }
  37722. uniform.offset = ( offset / this.bytesPerElement );
  37723. offset += ( itemSize * this.bytesPerElement );
  37724. }
  37725. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  37726. }
  37727. /**
  37728. * Updates this group by updating each uniform object of
  37729. * the internal uniform list. The uniform objects check if their
  37730. * values has actually changed so this method only returns
  37731. * `true` if there is a real value change.
  37732. *
  37733. * @return {boolean} Whether the uniforms have been updated and
  37734. * must be uploaded to the GPU.
  37735. */
  37736. update() {
  37737. let updated = false;
  37738. for ( const uniform of this.uniforms ) {
  37739. if ( this.updateByType( uniform ) === true ) {
  37740. updated = true;
  37741. }
  37742. }
  37743. return updated;
  37744. }
  37745. /**
  37746. * Updates a given uniform by calling an update method matching
  37747. * the uniforms type.
  37748. *
  37749. * @param {Uniform} uniform - The uniform to update.
  37750. * @return {boolean} Whether the uniform has been updated or not.
  37751. */
  37752. updateByType( uniform ) {
  37753. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  37754. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  37755. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  37756. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  37757. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  37758. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  37759. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  37760. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  37761. }
  37762. /**
  37763. * Updates a given Number uniform.
  37764. *
  37765. * @param {NumberUniform} uniform - The Number uniform.
  37766. * @return {boolean} Whether the uniform has been updated or not.
  37767. */
  37768. updateNumber( uniform ) {
  37769. let updated = false;
  37770. const a = this.values;
  37771. const v = uniform.getValue();
  37772. const offset = uniform.offset;
  37773. const type = uniform.getType();
  37774. if ( a[ offset ] !== v ) {
  37775. const b = this._getBufferForType( type );
  37776. b[ offset ] = a[ offset ] = v;
  37777. updated = true;
  37778. }
  37779. return updated;
  37780. }
  37781. /**
  37782. * Updates a given Vector2 uniform.
  37783. *
  37784. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  37785. * @return {boolean} Whether the uniform has been updated or not.
  37786. */
  37787. updateVector2( uniform ) {
  37788. let updated = false;
  37789. const a = this.values;
  37790. const v = uniform.getValue();
  37791. const offset = uniform.offset;
  37792. const type = uniform.getType();
  37793. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  37794. const b = this._getBufferForType( type );
  37795. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37796. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37797. updated = true;
  37798. }
  37799. return updated;
  37800. }
  37801. /**
  37802. * Updates a given Vector3 uniform.
  37803. *
  37804. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  37805. * @return {boolean} Whether the uniform has been updated or not.
  37806. */
  37807. updateVector3( uniform ) {
  37808. let updated = false;
  37809. const a = this.values;
  37810. const v = uniform.getValue();
  37811. const offset = uniform.offset;
  37812. const type = uniform.getType();
  37813. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  37814. const b = this._getBufferForType( type );
  37815. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37816. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37817. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37818. updated = true;
  37819. }
  37820. return updated;
  37821. }
  37822. /**
  37823. * Updates a given Vector4 uniform.
  37824. *
  37825. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  37826. * @return {boolean} Whether the uniform has been updated or not.
  37827. */
  37828. updateVector4( uniform ) {
  37829. let updated = false;
  37830. const a = this.values;
  37831. const v = uniform.getValue();
  37832. const offset = uniform.offset;
  37833. const type = uniform.getType();
  37834. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  37835. const b = this._getBufferForType( type );
  37836. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  37837. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  37838. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  37839. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  37840. updated = true;
  37841. }
  37842. return updated;
  37843. }
  37844. /**
  37845. * Updates a given Color uniform.
  37846. *
  37847. * @param {ColorUniform} uniform - The Color uniform.
  37848. * @return {boolean} Whether the uniform has been updated or not.
  37849. */
  37850. updateColor( uniform ) {
  37851. let updated = false;
  37852. const a = this.values;
  37853. const c = uniform.getValue();
  37854. const offset = uniform.offset;
  37855. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  37856. const b = this.buffer;
  37857. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  37858. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  37859. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  37860. updated = true;
  37861. }
  37862. return updated;
  37863. }
  37864. /**
  37865. * Updates a given Matrix3 uniform.
  37866. *
  37867. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  37868. * @return {boolean} Whether the uniform has been updated or not.
  37869. */
  37870. updateMatrix3( uniform ) {
  37871. let updated = false;
  37872. const a = this.values;
  37873. const e = uniform.getValue().elements;
  37874. const offset = uniform.offset;
  37875. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  37876. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  37877. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  37878. const b = this.buffer;
  37879. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  37880. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  37881. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  37882. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  37883. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  37884. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  37885. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  37886. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  37887. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  37888. updated = true;
  37889. }
  37890. return updated;
  37891. }
  37892. /**
  37893. * Updates a given Matrix4 uniform.
  37894. *
  37895. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  37896. * @return {boolean} Whether the uniform has been updated or not.
  37897. */
  37898. updateMatrix4( uniform ) {
  37899. let updated = false;
  37900. const a = this.values;
  37901. const e = uniform.getValue().elements;
  37902. const offset = uniform.offset;
  37903. if ( arraysEqual( a, e, offset ) === false ) {
  37904. const b = this.buffer;
  37905. b.set( e, offset );
  37906. setArray( a, e, offset );
  37907. updated = true;
  37908. }
  37909. return updated;
  37910. }
  37911. /**
  37912. * Returns a typed array that matches the given data type.
  37913. *
  37914. * @param {string} type - The data type.
  37915. * @return {TypedArray} The typed array.
  37916. */
  37917. _getBufferForType( type ) {
  37918. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  37919. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  37920. return this.buffer;
  37921. }
  37922. }
  37923. /**
  37924. * Sets the values of the second array to the first array.
  37925. *
  37926. * @private
  37927. * @param {TypedArray} a - The first array.
  37928. * @param {TypedArray} b - The second array.
  37929. * @param {number} offset - An index offset for the first array.
  37930. */
  37931. function setArray( a, b, offset ) {
  37932. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37933. a[ offset + i ] = b[ i ];
  37934. }
  37935. }
  37936. /**
  37937. * Returns `true` if the given arrays are equal.
  37938. *
  37939. * @private
  37940. * @param {TypedArray} a - The first array.
  37941. * @param {TypedArray} b - The second array.
  37942. * @param {number} offset - An index offset for the first array.
  37943. * @return {boolean} Whether the given arrays are equal or not.
  37944. */
  37945. function arraysEqual( a, b, offset ) {
  37946. for ( let i = 0, l = b.length; i < l; i ++ ) {
  37947. if ( a[ offset + i ] !== b[ i ] ) return false;
  37948. }
  37949. return true;
  37950. }
  37951. let _id$3 = 0;
  37952. /**
  37953. * A special form of uniforms group that represents
  37954. * the individual uniforms as node-based uniforms.
  37955. *
  37956. * @private
  37957. * @augments UniformsGroup
  37958. */
  37959. class NodeUniformsGroup extends UniformsGroup {
  37960. /**
  37961. * Constructs a new node-based uniforms group.
  37962. *
  37963. * @param {string} name - The group's name.
  37964. * @param {UniformGroupNode} groupNode - The uniform group node.
  37965. */
  37966. constructor( name, groupNode ) {
  37967. super( name );
  37968. /**
  37969. * The group's ID.
  37970. *
  37971. * @type {number}
  37972. */
  37973. this.id = _id$3 ++;
  37974. /**
  37975. * The uniform group node.
  37976. *
  37977. * @type {UniformGroupNode}
  37978. */
  37979. this.groupNode = groupNode;
  37980. /**
  37981. * This flag can be used for type testing.
  37982. *
  37983. * @type {boolean}
  37984. * @readonly
  37985. * @default true
  37986. */
  37987. this.isNodeUniformsGroup = true;
  37988. }
  37989. }
  37990. let _id$2 = 0;
  37991. /**
  37992. * Represents a sampled texture binding type.
  37993. *
  37994. * @private
  37995. * @augments Binding
  37996. */
  37997. class SampledTexture extends Binding {
  37998. /**
  37999. * Constructs a new sampled texture.
  38000. *
  38001. * @param {string} name - The sampled texture's name.
  38002. * @param {?Texture} texture - The texture this binding is referring to.
  38003. */
  38004. constructor( name, texture ) {
  38005. super( name );
  38006. /**
  38007. * This identifier.
  38008. *
  38009. * @type {number}
  38010. */
  38011. this.id = _id$2 ++;
  38012. /**
  38013. * The texture this binding is referring to.
  38014. *
  38015. * @type {?Texture}
  38016. */
  38017. this.texture = texture;
  38018. /**
  38019. * The binding's version.
  38020. *
  38021. * @type {number}
  38022. */
  38023. this.version = texture ? texture.version : 0;
  38024. /**
  38025. * Whether the texture is a storage texture or not.
  38026. *
  38027. * @type {boolean}
  38028. * @default false
  38029. */
  38030. this.store = false;
  38031. /**
  38032. * The binding's generation which is an additional version
  38033. * qualifier.
  38034. *
  38035. * @type {?number}
  38036. * @default null
  38037. */
  38038. this.generation = null;
  38039. /**
  38040. * This flag can be used for type testing.
  38041. *
  38042. * @type {boolean}
  38043. * @readonly
  38044. * @default true
  38045. */
  38046. this.isSampledTexture = true;
  38047. }
  38048. /**
  38049. * Returns `true` whether this binding requires an update for the
  38050. * given generation.
  38051. *
  38052. * @param {number} generation - The generation.
  38053. * @return {boolean} Whether an update is required or not.
  38054. */
  38055. needsBindingsUpdate( generation ) {
  38056. const { texture } = this;
  38057. if ( generation !== this.generation ) {
  38058. this.generation = generation;
  38059. return true;
  38060. }
  38061. return texture.isVideoTexture;
  38062. }
  38063. /**
  38064. * Updates the binding.
  38065. *
  38066. * @return {boolean} Whether the texture has been updated and must be
  38067. * uploaded to the GPU.
  38068. */
  38069. update() {
  38070. const { texture, version } = this;
  38071. if ( version !== texture.version ) {
  38072. this.version = texture.version;
  38073. return true;
  38074. }
  38075. return false;
  38076. }
  38077. }
  38078. /**
  38079. * A special form of sampled texture binding type.
  38080. * It's texture value is managed by a node object.
  38081. *
  38082. * @private
  38083. * @augments SampledTexture
  38084. */
  38085. class NodeSampledTexture extends SampledTexture {
  38086. /**
  38087. * Constructs a new node-based sampled texture.
  38088. *
  38089. * @param {string} name - The textures's name.
  38090. * @param {TextureNode} textureNode - The texture node.
  38091. * @param {UniformGroupNode} groupNode - The uniform group node.
  38092. * @param {?string} [access=null] - The access type.
  38093. */
  38094. constructor( name, textureNode, groupNode, access = null ) {
  38095. super( name, textureNode ? textureNode.value : null );
  38096. /**
  38097. * The texture node.
  38098. *
  38099. * @type {TextureNode}
  38100. */
  38101. this.textureNode = textureNode;
  38102. /**
  38103. * The uniform group node.
  38104. *
  38105. * @type {UniformGroupNode}
  38106. */
  38107. this.groupNode = groupNode;
  38108. /**
  38109. * The access type.
  38110. *
  38111. * @type {?string}
  38112. * @default null
  38113. */
  38114. this.access = access;
  38115. }
  38116. /**
  38117. * Overwrites the default to additionally check if the node value has changed.
  38118. *
  38119. * @param {number} generation - The generation.
  38120. * @return {boolean} Whether an update is required or not.
  38121. */
  38122. needsBindingsUpdate( generation ) {
  38123. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  38124. }
  38125. /**
  38126. * Updates the binding.
  38127. *
  38128. * @return {boolean} Whether the texture has been updated and must be
  38129. * uploaded to the GPU.
  38130. */
  38131. update() {
  38132. const { textureNode } = this;
  38133. if ( this.texture !== textureNode.value ) {
  38134. this.texture = textureNode.value;
  38135. return true;
  38136. }
  38137. return super.update();
  38138. }
  38139. }
  38140. /**
  38141. * A special form of sampled cube texture binding type.
  38142. * It's texture value is managed by a node object.
  38143. *
  38144. * @private
  38145. * @augments NodeSampledTexture
  38146. */
  38147. class NodeSampledCubeTexture extends NodeSampledTexture {
  38148. /**
  38149. * Constructs a new node-based sampled cube texture.
  38150. *
  38151. * @param {string} name - The textures's name.
  38152. * @param {TextureNode} textureNode - The texture node.
  38153. * @param {UniformGroupNode} groupNode - The uniform group node.
  38154. * @param {?string} [access=null] - The access type.
  38155. */
  38156. constructor( name, textureNode, groupNode, access = null ) {
  38157. super( name, textureNode, groupNode, access );
  38158. /**
  38159. * This flag can be used for type testing.
  38160. *
  38161. * @type {boolean}
  38162. * @readonly
  38163. * @default true
  38164. */
  38165. this.isSampledCubeTexture = true;
  38166. }
  38167. }
  38168. /**
  38169. * A special form of sampled 3D texture binding type.
  38170. * It's texture value is managed by a node object.
  38171. *
  38172. * @private
  38173. * @augments NodeSampledTexture
  38174. */
  38175. class NodeSampledTexture3D extends NodeSampledTexture {
  38176. /**
  38177. * Constructs a new node-based sampled 3D texture.
  38178. *
  38179. * @param {string} name - The textures's name.
  38180. * @param {TextureNode} textureNode - The texture node.
  38181. * @param {UniformGroupNode} groupNode - The uniform group node.
  38182. * @param {?string} [access=null] - The access type.
  38183. */
  38184. constructor( name, textureNode, groupNode, access = null ) {
  38185. super( name, textureNode, groupNode, access );
  38186. /**
  38187. * This flag can be used for type testing.
  38188. *
  38189. * @type {boolean}
  38190. * @readonly
  38191. * @default true
  38192. */
  38193. this.isSampledTexture3D = true;
  38194. }
  38195. }
  38196. const glslMethods = {
  38197. textureDimensions: 'textureSize',
  38198. equals: 'equal'
  38199. };
  38200. const precisionLib = {
  38201. low: 'lowp',
  38202. medium: 'mediump',
  38203. high: 'highp'
  38204. };
  38205. const supports$1 = {
  38206. swizzleAssign: true,
  38207. storageBuffer: false
  38208. };
  38209. const defaultPrecisions = `
  38210. precision highp float;
  38211. precision highp int;
  38212. precision highp sampler2D;
  38213. precision highp sampler3D;
  38214. precision highp samplerCube;
  38215. precision highp sampler2DArray;
  38216. precision highp usampler2D;
  38217. precision highp usampler3D;
  38218. precision highp usamplerCube;
  38219. precision highp usampler2DArray;
  38220. precision highp isampler2D;
  38221. precision highp isampler3D;
  38222. precision highp isamplerCube;
  38223. precision highp isampler2DArray;
  38224. precision lowp sampler2DShadow;
  38225. `;
  38226. /**
  38227. * A node builder targeting GLSL.
  38228. *
  38229. * This module generates GLSL shader code from node materials and also
  38230. * generates the respective bindings and vertex buffer definitions. These
  38231. * data are later used by the renderer to create render and compute pipelines
  38232. * for render objects.
  38233. *
  38234. * @augments NodeBuilder
  38235. */
  38236. class GLSLNodeBuilder extends NodeBuilder {
  38237. /**
  38238. * Constructs a new GLSL node builder renderer.
  38239. *
  38240. * @param {Object3D} object - The 3D object.
  38241. * @param {Renderer} renderer - The renderer.
  38242. */
  38243. constructor( object, renderer ) {
  38244. super( object, renderer, new GLSLNodeParser() );
  38245. /**
  38246. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  38247. * another dictionary which manages UBOs per group ('render','frame','object').
  38248. *
  38249. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  38250. */
  38251. this.uniformGroups = {};
  38252. /**
  38253. * An array that holds objects defining the varying and attribute data in
  38254. * context of Transform Feedback.
  38255. *
  38256. * @type {Array<Object<string,AttributeNode|string>>}
  38257. */
  38258. this.transforms = [];
  38259. /**
  38260. * A dictionary that holds for each shader stage a Map of used extensions.
  38261. *
  38262. * @type {Object<string,Map<string,Object>>}
  38263. */
  38264. this.extensions = {};
  38265. /**
  38266. * A dictionary that holds for each shader stage an Array of used builtins.
  38267. *
  38268. * @type {Object<string,Array<string>>}
  38269. */
  38270. this.builtins = { vertex: [], fragment: [], compute: [] };
  38271. /**
  38272. * Whether comparison in shader code are generated with methods or not.
  38273. *
  38274. * @type {boolean}
  38275. * @default true
  38276. */
  38277. this.useComparisonMethod = true;
  38278. }
  38279. /**
  38280. * Checks if the given texture requires a manual conversion to the working color space.
  38281. *
  38282. * @param {Texture} texture - The texture to check.
  38283. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  38284. */
  38285. needsToWorkingColorSpace( texture ) {
  38286. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  38287. }
  38288. /**
  38289. * Returns the native shader method name for a given generic name.
  38290. *
  38291. * @param {string} method - The method name to resolve.
  38292. * @return {string} The resolved GLSL method name.
  38293. */
  38294. getMethod( method ) {
  38295. return glslMethods[ method ] || method;
  38296. }
  38297. /**
  38298. * Returns the output struct name. Not relevant for GLSL.
  38299. *
  38300. * @return {string}
  38301. */
  38302. getOutputStructName() {
  38303. return '';
  38304. }
  38305. /**
  38306. * Builds the given shader node.
  38307. *
  38308. * @param {ShaderNodeInternal} shaderNode - The shader node.
  38309. * @return {string} The GLSL function code.
  38310. */
  38311. buildFunctionCode( shaderNode ) {
  38312. const layout = shaderNode.layout;
  38313. const flowData = this.flowShaderNode( shaderNode );
  38314. const parameters = [];
  38315. for ( const input of layout.inputs ) {
  38316. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38317. }
  38318. //
  38319. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38320. ${ flowData.vars }
  38321. ${ flowData.code }
  38322. return ${ flowData.result };
  38323. }`;
  38324. //
  38325. return code;
  38326. }
  38327. /**
  38328. * Setups the Pixel Buffer Object (PBO) for the given storage
  38329. * buffer node.
  38330. *
  38331. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  38332. */
  38333. setupPBO( storageBufferNode ) {
  38334. const attribute = storageBufferNode.value;
  38335. if ( attribute.pbo === undefined ) {
  38336. const originalArray = attribute.array;
  38337. const numElements = attribute.count * attribute.itemSize;
  38338. const { itemSize } = attribute;
  38339. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38340. let format = isInteger ? RedIntegerFormat : RedFormat;
  38341. if ( itemSize === 2 ) {
  38342. format = isInteger ? RGIntegerFormat : RGFormat;
  38343. } else if ( itemSize === 3 ) {
  38344. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38345. } else if ( itemSize === 4 ) {
  38346. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38347. }
  38348. const typeMap = {
  38349. Float32Array: FloatType,
  38350. Uint8Array: UnsignedByteType,
  38351. Uint16Array: UnsignedShortType,
  38352. Uint32Array: UnsignedIntType,
  38353. Int8Array: ByteType,
  38354. Int16Array: ShortType,
  38355. Int32Array: IntType,
  38356. Uint8ClampedArray: UnsignedByteType,
  38357. };
  38358. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38359. let height = Math.ceil( ( numElements / itemSize ) / width );
  38360. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38361. const newSize = width * height * itemSize;
  38362. const newArray = new originalArray.constructor( newSize );
  38363. newArray.set( originalArray, 0 );
  38364. attribute.array = newArray;
  38365. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38366. pboTexture.needsUpdate = true;
  38367. pboTexture.isPBOTexture = true;
  38368. const pbo = new TextureNode( pboTexture, null, null );
  38369. pbo.setPrecision( 'high' );
  38370. attribute.pboNode = pbo;
  38371. attribute.pbo = pbo.value;
  38372. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38373. }
  38374. }
  38375. /**
  38376. * Returns a GLSL snippet that represents the property name of the given node.
  38377. *
  38378. * @param {Node} node - The node.
  38379. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  38380. * @return {string} The property name.
  38381. */
  38382. getPropertyName( node, shaderStage = this.shaderStage ) {
  38383. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38384. return shaderStage.charAt( 0 ) + '_' + node.name;
  38385. }
  38386. return super.getPropertyName( node, shaderStage );
  38387. }
  38388. /**
  38389. * Setups the Pixel Buffer Object (PBO) for the given storage
  38390. * buffer node.
  38391. *
  38392. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  38393. * @return {string} The property name.
  38394. */
  38395. generatePBO( storageArrayElementNode ) {
  38396. const { node, indexNode } = storageArrayElementNode;
  38397. const attribute = node.value;
  38398. if ( this.renderer.backend.has( attribute ) ) {
  38399. const attributeData = this.renderer.backend.get( attribute );
  38400. attributeData.pbo = attribute.pbo;
  38401. }
  38402. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38403. const textureName = this.getPropertyName( nodeUniform );
  38404. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  38405. const indexSnippet = indexNode.build( this, 'uint' );
  38406. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38407. let propertyName = elementNodeData.propertyName;
  38408. if ( propertyName === undefined ) {
  38409. // property element
  38410. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38411. propertyName = this.getPropertyName( nodeVar );
  38412. // property size
  38413. const bufferNodeData = this.getDataFromNode( node );
  38414. let propertySizeName = bufferNodeData.propertySizeName;
  38415. if ( propertySizeName === undefined ) {
  38416. propertySizeName = propertyName + 'Size';
  38417. this.getVarFromNode( node, propertySizeName, 'uint' );
  38418. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  38419. bufferNodeData.propertySizeName = propertySizeName;
  38420. }
  38421. //
  38422. const { itemSize } = attribute;
  38423. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38424. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38425. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38426. //
  38427. let prefix = 'vec4';
  38428. if ( attribute.pbo.type === UnsignedIntType ) {
  38429. prefix = 'uvec4';
  38430. } else if ( attribute.pbo.type === IntType ) {
  38431. prefix = 'ivec4';
  38432. }
  38433. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  38434. elementNodeData.propertyName = propertyName;
  38435. }
  38436. return propertyName;
  38437. }
  38438. /**
  38439. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  38440. *
  38441. * @param {Texture} texture - The texture.
  38442. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38443. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38444. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  38445. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  38446. * @return {string} The GLSL snippet.
  38447. */
  38448. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38449. if ( depthSnippet ) {
  38450. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38451. } else {
  38452. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38453. }
  38454. }
  38455. /**
  38456. * Generates the GLSL snippet for sampling/loading the given texture.
  38457. *
  38458. * @param {Texture} texture - The texture.
  38459. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38460. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38461. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  38462. * @return {string} The GLSL snippet.
  38463. */
  38464. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38465. if ( texture.isDepthTexture ) {
  38466. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38467. } else {
  38468. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38469. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38470. }
  38471. }
  38472. /**
  38473. * Generates the GLSL snippet when sampling textures with explicit mip level.
  38474. *
  38475. * @param {Texture} texture - The texture.
  38476. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38477. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38478. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  38479. * @return {string} The GLSL snippet.
  38480. */
  38481. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38482. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38483. }
  38484. /**
  38485. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  38486. *
  38487. * @param {Texture} texture - The texture.
  38488. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38489. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38490. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  38491. * @return {string} The GLSL snippet.
  38492. */
  38493. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38494. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38495. }
  38496. /**
  38497. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  38498. *
  38499. * @param {Texture} texture - The texture.
  38500. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38501. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38502. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  38503. * @return {string} The GLSL snippet.
  38504. */
  38505. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38506. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38507. }
  38508. /**
  38509. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  38510. * against a reference value.
  38511. *
  38512. * @param {Texture} texture - The texture.
  38513. * @param {string} textureProperty - The name of the texture uniform in the shader.
  38514. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  38515. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  38516. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  38517. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  38518. * @return {string} The GLSL snippet.
  38519. */
  38520. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38521. if ( shaderStage === 'fragment' ) {
  38522. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38523. } else {
  38524. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38525. }
  38526. }
  38527. /**
  38528. * Returns the variables of the given shader stage as a GLSL string.
  38529. *
  38530. * @param {string} shaderStage - The shader stage.
  38531. * @return {string} The GLSL snippet that defines the variables.
  38532. */
  38533. getVars( shaderStage ) {
  38534. const snippets = [];
  38535. const vars = this.vars[ shaderStage ];
  38536. if ( vars !== undefined ) {
  38537. for ( const variable of vars ) {
  38538. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  38539. }
  38540. }
  38541. return snippets.join( '\n\t' );
  38542. }
  38543. /**
  38544. * Returns the uniforms of the given shader stage as a GLSL string.
  38545. *
  38546. * @param {string} shaderStage - The shader stage.
  38547. * @return {string} The GLSL snippet that defines the uniforms.
  38548. */
  38549. getUniforms( shaderStage ) {
  38550. const uniforms = this.uniforms[ shaderStage ];
  38551. const bindingSnippets = [];
  38552. const uniformGroups = {};
  38553. for ( const uniform of uniforms ) {
  38554. let snippet = null;
  38555. let group = false;
  38556. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  38557. const texture = uniform.node.value;
  38558. let typePrefix = '';
  38559. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  38560. if ( texture.type === UnsignedIntType ) {
  38561. typePrefix = 'u';
  38562. } else if ( texture.type === IntType ) {
  38563. typePrefix = 'i';
  38564. }
  38565. }
  38566. if ( uniform.type === 'texture3D' ) {
  38567. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  38568. } else if ( texture.compareFunction ) {
  38569. snippet = `sampler2DShadow ${ uniform.name };`;
  38570. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  38571. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38572. } else {
  38573. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38574. }
  38575. } else if ( uniform.type === 'cubeTexture' ) {
  38576. snippet = `samplerCube ${ uniform.name };`;
  38577. } else if ( uniform.type === 'buffer' ) {
  38578. const bufferNode = uniform.node;
  38579. const bufferType = this.getType( bufferNode.bufferType );
  38580. const bufferCount = bufferNode.bufferCount;
  38581. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38582. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38583. } else {
  38584. const vectorType = this.getVectorType( uniform.type );
  38585. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38586. group = true;
  38587. }
  38588. const precision = uniform.node.precision;
  38589. if ( precision !== null ) {
  38590. snippet = precisionLib[ precision ] + ' ' + snippet;
  38591. }
  38592. if ( group ) {
  38593. snippet = '\t' + snippet;
  38594. const groupName = uniform.groupNode.name;
  38595. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38596. groupSnippets.push( snippet );
  38597. } else {
  38598. snippet = 'uniform ' + snippet;
  38599. bindingSnippets.push( snippet );
  38600. }
  38601. }
  38602. let output = '';
  38603. for ( const name in uniformGroups ) {
  38604. const groupSnippets = uniformGroups[ name ];
  38605. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38606. }
  38607. output += bindingSnippets.join( '\n' );
  38608. return output;
  38609. }
  38610. /**
  38611. * Returns the type for a given buffer attribute.
  38612. *
  38613. * @param {BufferAttribute} attribute - The buffer attribute.
  38614. * @return {string} The type.
  38615. */
  38616. getTypeFromAttribute( attribute ) {
  38617. let nodeType = super.getTypeFromAttribute( attribute );
  38618. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38619. let dataAttribute = attribute;
  38620. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38621. const array = dataAttribute.array;
  38622. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38623. nodeType = nodeType.slice( 1 );
  38624. }
  38625. }
  38626. return nodeType;
  38627. }
  38628. /**
  38629. * Returns the shader attributes of the given shader stage as a GLSL string.
  38630. *
  38631. * @param {string} shaderStage - The shader stage.
  38632. * @return {string} The GLSL snippet that defines the shader attributes.
  38633. */
  38634. getAttributes( shaderStage ) {
  38635. let snippet = '';
  38636. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38637. const attributes = this.getAttributesArray();
  38638. let location = 0;
  38639. for ( const attribute of attributes ) {
  38640. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38641. }
  38642. }
  38643. return snippet;
  38644. }
  38645. /**
  38646. * Returns the members of the given struct type node as a GLSL string.
  38647. *
  38648. * @param {StructTypeNode} struct - The struct type node.
  38649. * @return {string} The GLSL snippet that defines the struct members.
  38650. */
  38651. getStructMembers( struct ) {
  38652. const snippets = [];
  38653. for ( const member of struct.members ) {
  38654. snippets.push( `\t${ member.type } ${ member.name };` );
  38655. }
  38656. return snippets.join( '\n' );
  38657. }
  38658. /**
  38659. * Returns the structs of the given shader stage as a GLSL string.
  38660. *
  38661. * @param {string} shaderStage - The shader stage.
  38662. * @return {string} The GLSL snippet that defines the structs.
  38663. */
  38664. getStructs( shaderStage ) {
  38665. const snippets = [];
  38666. const structs = this.structs[ shaderStage ];
  38667. const outputSnippet = [];
  38668. for ( const struct of structs ) {
  38669. if ( struct.output ) {
  38670. for ( const member of struct.members ) {
  38671. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  38672. }
  38673. } else {
  38674. let snippet = 'struct ' + struct.name + ' {\n';
  38675. snippet += this.getStructMembers( struct );
  38676. snippet += '\n};\n';
  38677. snippets.push( snippet );
  38678. }
  38679. }
  38680. if ( outputSnippet.length === 0 ) {
  38681. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  38682. }
  38683. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  38684. }
  38685. /**
  38686. * Returns the varyings of the given shader stage as a GLSL string.
  38687. *
  38688. * @param {string} shaderStage - The shader stage.
  38689. * @return {string} The GLSL snippet that defines the varyings.
  38690. */
  38691. getVaryings( shaderStage ) {
  38692. let snippet = '';
  38693. const varyings = this.varyings;
  38694. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38695. for ( const varying of varyings ) {
  38696. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38697. const type = this.getType( varying.type );
  38698. if ( varying.needsInterpolation ) {
  38699. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38700. snippet += `${flat} out ${type} ${varying.name};\n`;
  38701. } else {
  38702. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  38703. }
  38704. }
  38705. } else if ( shaderStage === 'fragment' ) {
  38706. for ( const varying of varyings ) {
  38707. if ( varying.needsInterpolation ) {
  38708. const type = this.getType( varying.type );
  38709. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38710. snippet += `${flat}in ${type} ${varying.name};\n`;
  38711. }
  38712. }
  38713. }
  38714. for ( const builtin of this.builtins[ shaderStage ] ) {
  38715. snippet += `${builtin};\n`;
  38716. }
  38717. return snippet;
  38718. }
  38719. /**
  38720. * Returns the vertex index builtin.
  38721. *
  38722. * @return {string} The vertex index.
  38723. */
  38724. getVertexIndex() {
  38725. return 'uint( gl_VertexID )';
  38726. }
  38727. /**
  38728. * Returns the instance index builtin.
  38729. *
  38730. * @return {string} The instance index.
  38731. */
  38732. getInstanceIndex() {
  38733. return 'uint( gl_InstanceID )';
  38734. }
  38735. /**
  38736. * Returns the invocation local index builtin.
  38737. *
  38738. * @return {string} The invocation local index.
  38739. */
  38740. getInvocationLocalIndex() {
  38741. const workgroupSize = this.object.workgroupSize;
  38742. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  38743. return `uint( gl_InstanceID ) % ${size}u`;
  38744. }
  38745. /**
  38746. * Returns the draw index builtin.
  38747. *
  38748. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  38749. */
  38750. getDrawIndex() {
  38751. const extensions = this.renderer.backend.extensions;
  38752. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38753. return 'uint( gl_DrawID )';
  38754. }
  38755. return null;
  38756. }
  38757. /**
  38758. * Returns the front facing builtin.
  38759. *
  38760. * @return {string} The front facing builtin.
  38761. */
  38762. getFrontFacing() {
  38763. return 'gl_FrontFacing';
  38764. }
  38765. /**
  38766. * Returns the frag coord builtin.
  38767. *
  38768. * @return {string} The frag coord builtin.
  38769. */
  38770. getFragCoord() {
  38771. return 'gl_FragCoord.xy';
  38772. }
  38773. /**
  38774. * Returns the frag depth builtin.
  38775. *
  38776. * @return {string} The frag depth builtin.
  38777. */
  38778. getFragDepth() {
  38779. return 'gl_FragDepth';
  38780. }
  38781. /**
  38782. * Enables the given extension.
  38783. *
  38784. * @param {string} name - The extension name.
  38785. * @param {string} behavior - The extension behavior.
  38786. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  38787. */
  38788. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  38789. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  38790. if ( map.has( name ) === false ) {
  38791. map.set( name, {
  38792. name,
  38793. behavior
  38794. } );
  38795. }
  38796. }
  38797. /**
  38798. * Returns the enabled extensions of the given shader stage as a GLSL string.
  38799. *
  38800. * @param {string} shaderStage - The shader stage.
  38801. * @return {string} The GLSL snippet that defines the enabled extensions.
  38802. */
  38803. getExtensions( shaderStage ) {
  38804. const snippets = [];
  38805. if ( shaderStage === 'vertex' ) {
  38806. const ext = this.renderer.backend.extensions;
  38807. const isBatchedMesh = this.object.isBatchedMesh;
  38808. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38809. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  38810. }
  38811. }
  38812. const extensions = this.extensions[ shaderStage ];
  38813. if ( extensions !== undefined ) {
  38814. for ( const { name, behavior } of extensions.values() ) {
  38815. snippets.push( `#extension ${name} : ${behavior}` );
  38816. }
  38817. }
  38818. return snippets.join( '\n' );
  38819. }
  38820. /**
  38821. * Returns the clip distances builtin.
  38822. *
  38823. * @return {string} The clip distances builtin.
  38824. */
  38825. getClipDistance() {
  38826. return 'gl_ClipDistance';
  38827. }
  38828. /**
  38829. * Whether the requested feature is available or not.
  38830. *
  38831. * @param {string} name - The requested feature.
  38832. * @return {boolean} Whether the requested feature is supported or not.
  38833. */
  38834. isAvailable( name ) {
  38835. let result = supports$1[ name ];
  38836. if ( result === undefined ) {
  38837. let extensionName;
  38838. result = false;
  38839. switch ( name ) {
  38840. case 'float32Filterable':
  38841. extensionName = 'OES_texture_float_linear';
  38842. break;
  38843. case 'clipDistance':
  38844. extensionName = 'WEBGL_clip_cull_distance';
  38845. break;
  38846. }
  38847. if ( extensionName !== undefined ) {
  38848. const extensions = this.renderer.backend.extensions;
  38849. if ( extensions.has( extensionName ) ) {
  38850. extensions.get( extensionName );
  38851. result = true;
  38852. }
  38853. }
  38854. supports$1[ name ] = result;
  38855. }
  38856. return result;
  38857. }
  38858. /**
  38859. * Whether to flip texture data along its vertical axis or not.
  38860. *
  38861. * @return {boolean} Returns always `true` in context of GLSL.
  38862. */
  38863. isFlipY() {
  38864. return true;
  38865. }
  38866. /**
  38867. * Enables hardware clipping.
  38868. *
  38869. * @param {string} planeCount - The clipping plane count.
  38870. */
  38871. enableHardwareClipping( planeCount ) {
  38872. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  38873. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  38874. }
  38875. /**
  38876. * Registers a transform in context of Transform Feedback.
  38877. *
  38878. * @param {string} varyingName - The varying name.
  38879. * @param {AttributeNode} attributeNode - The attribute node.
  38880. */
  38881. registerTransform( varyingName, attributeNode ) {
  38882. this.transforms.push( { varyingName, attributeNode } );
  38883. }
  38884. /**
  38885. * Returns the transforms of the given shader stage as a GLSL string.
  38886. *
  38887. * @param {string} shaderStage - The shader stage.
  38888. * @return {string} The GLSL snippet that defines the transforms.
  38889. */
  38890. getTransforms( /* shaderStage */ ) {
  38891. const transforms = this.transforms;
  38892. let snippet = '';
  38893. for ( let i = 0; i < transforms.length; i ++ ) {
  38894. const transform = transforms[ i ];
  38895. const attributeName = this.getPropertyName( transform.attributeNode );
  38896. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  38897. }
  38898. return snippet;
  38899. }
  38900. /**
  38901. * Returns a GLSL struct based on the given name and variables.
  38902. *
  38903. * @private
  38904. * @param {string} name - The struct name.
  38905. * @param {string} vars - The struct variables.
  38906. * @return {string} The GLSL snippet representing a struct.
  38907. */
  38908. _getGLSLUniformStruct( name, vars ) {
  38909. return `
  38910. layout( std140 ) uniform ${name} {
  38911. ${vars}
  38912. };`;
  38913. }
  38914. /**
  38915. * Returns a GLSL vertex shader based on the given shader data.
  38916. *
  38917. * @private
  38918. * @param {Object} shaderData - The shader data.
  38919. * @return {string} The vertex shader.
  38920. */
  38921. _getGLSLVertexCode( shaderData ) {
  38922. return `#version 300 es
  38923. ${ this.getSignature() }
  38924. // extensions
  38925. ${shaderData.extensions}
  38926. // precision
  38927. ${ defaultPrecisions }
  38928. // uniforms
  38929. ${shaderData.uniforms}
  38930. // varyings
  38931. ${shaderData.varyings}
  38932. // attributes
  38933. ${shaderData.attributes}
  38934. // codes
  38935. ${shaderData.codes}
  38936. void main() {
  38937. // vars
  38938. ${shaderData.vars}
  38939. // transforms
  38940. ${shaderData.transforms}
  38941. // flow
  38942. ${shaderData.flow}
  38943. gl_PointSize = 1.0;
  38944. }
  38945. `;
  38946. }
  38947. /**
  38948. * Returns a GLSL fragment shader based on the given shader data.
  38949. *
  38950. * @private
  38951. * @param {Object} shaderData - The shader data.
  38952. * @return {string} The vertex shader.
  38953. */
  38954. _getGLSLFragmentCode( shaderData ) {
  38955. return `#version 300 es
  38956. ${ this.getSignature() }
  38957. // precision
  38958. ${ defaultPrecisions }
  38959. // uniforms
  38960. ${shaderData.uniforms}
  38961. // varyings
  38962. ${shaderData.varyings}
  38963. // codes
  38964. ${shaderData.codes}
  38965. // structs
  38966. ${shaderData.structs}
  38967. void main() {
  38968. // vars
  38969. ${shaderData.vars}
  38970. // flow
  38971. ${shaderData.flow}
  38972. }
  38973. `;
  38974. }
  38975. /**
  38976. * Controls the code build of the shader stages.
  38977. */
  38978. buildCode() {
  38979. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  38980. this.sortBindingGroups();
  38981. for ( const shaderStage in shadersData ) {
  38982. let flow = '// code\n\n';
  38983. flow += this.flowCode[ shaderStage ];
  38984. const flowNodes = this.flowNodes[ shaderStage ];
  38985. const mainNode = flowNodes[ flowNodes.length - 1 ];
  38986. for ( const node of flowNodes ) {
  38987. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  38988. const slotName = node.name;
  38989. if ( slotName ) {
  38990. if ( flow.length > 0 ) flow += '\n';
  38991. flow += `\t// flow -> ${ slotName }\n\t`;
  38992. }
  38993. flow += `${ flowSlotData.code }\n\t`;
  38994. if ( node === mainNode && shaderStage !== 'compute' ) {
  38995. flow += '// result\n\t';
  38996. if ( shaderStage === 'vertex' ) {
  38997. flow += 'gl_Position = ';
  38998. flow += `${ flowSlotData.result };`;
  38999. } else if ( shaderStage === 'fragment' ) {
  39000. if ( ! node.outputNode.isOutputStructNode ) {
  39001. flow += 'fragColor = ';
  39002. flow += `${ flowSlotData.result };`;
  39003. }
  39004. }
  39005. }
  39006. }
  39007. const stageData = shadersData[ shaderStage ];
  39008. stageData.extensions = this.getExtensions( shaderStage );
  39009. stageData.uniforms = this.getUniforms( shaderStage );
  39010. stageData.attributes = this.getAttributes( shaderStage );
  39011. stageData.varyings = this.getVaryings( shaderStage );
  39012. stageData.vars = this.getVars( shaderStage );
  39013. stageData.structs = this.getStructs( shaderStage );
  39014. stageData.codes = this.getCodes( shaderStage );
  39015. stageData.transforms = this.getTransforms( shaderStage );
  39016. stageData.flow = flow;
  39017. }
  39018. if ( this.material !== null ) {
  39019. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39020. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39021. } else {
  39022. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39023. }
  39024. }
  39025. /**
  39026. * This method is one of the more important ones since it's responsible
  39027. * for generating a matching binding instance for the given uniform node.
  39028. *
  39029. * These bindings are later used in the renderer to create bind groups
  39030. * and layouts.
  39031. *
  39032. * @param {UniformNode} node - The uniform node.
  39033. * @param {string} type - The node data type.
  39034. * @param {string} shaderStage - The shader stage.
  39035. * @param {?string} [name=null] - An optional uniform name.
  39036. * @return {NodeUniform} The node uniform object.
  39037. */
  39038. getUniformFromNode( node, type, shaderStage, name = null ) {
  39039. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39040. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39041. let uniformGPU = nodeData.uniformGPU;
  39042. if ( uniformGPU === undefined ) {
  39043. const group = node.groupNode;
  39044. const groupName = group.name;
  39045. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39046. if ( type === 'texture' ) {
  39047. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39048. bindings.push( uniformGPU );
  39049. } else if ( type === 'cubeTexture' ) {
  39050. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39051. bindings.push( uniformGPU );
  39052. } else if ( type === 'texture3D' ) {
  39053. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39054. bindings.push( uniformGPU );
  39055. } else if ( type === 'buffer' ) {
  39056. node.name = `NodeBuffer_${ node.id }`;
  39057. uniformNode.name = `buffer${ node.id }`;
  39058. const buffer = new NodeUniformBuffer( node, group );
  39059. buffer.name = node.name;
  39060. bindings.push( buffer );
  39061. uniformGPU = buffer;
  39062. } else {
  39063. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39064. let uniformsGroup = uniformsStage[ groupName ];
  39065. if ( uniformsGroup === undefined ) {
  39066. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39067. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39068. uniformsStage[ groupName ] = uniformsGroup;
  39069. bindings.push( uniformsGroup );
  39070. }
  39071. uniformGPU = this.getNodeUniform( uniformNode, type );
  39072. uniformsGroup.addUniform( uniformGPU );
  39073. }
  39074. nodeData.uniformGPU = uniformGPU;
  39075. }
  39076. return uniformNode;
  39077. }
  39078. }
  39079. let _vector2 = null;
  39080. let _color4 = null;
  39081. /**
  39082. * Most of the rendering related logic is implemented in the
  39083. * {@link Renderer} module and related management components.
  39084. * Sometimes it is required though to execute commands which are
  39085. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  39086. * This abstract base class defines an interface that encapsulates
  39087. * all backend-related logic. Derived classes for each backend must
  39088. * implement the interface.
  39089. *
  39090. * @abstract
  39091. * @private
  39092. */
  39093. class Backend {
  39094. /**
  39095. * Constructs a new backend.
  39096. *
  39097. * @param {Object} parameters - An object holding parameters for the backend.
  39098. */
  39099. constructor( parameters = {} ) {
  39100. /**
  39101. * The parameters of the backend.
  39102. *
  39103. * @type {Object}
  39104. */
  39105. this.parameters = Object.assign( {}, parameters );
  39106. /**
  39107. * This weak map holds backend-specific data of objects
  39108. * like textures, attributes or render targets.
  39109. *
  39110. * @type {WeakMap}
  39111. */
  39112. this.data = new WeakMap();
  39113. /**
  39114. * A reference to the renderer.
  39115. *
  39116. * @type {?Renderer}
  39117. * @default null
  39118. */
  39119. this.renderer = null;
  39120. /**
  39121. * A reference to the canvas element the renderer is drawing to.
  39122. *
  39123. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  39124. * @default null
  39125. */
  39126. this.domElement = null;
  39127. /**
  39128. * A reference to the timestamp query pool.
  39129. *
  39130. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  39131. */
  39132. this.timestampQueryPool = {
  39133. 'render': null,
  39134. 'compute': null
  39135. };
  39136. /**
  39137. * Whether to track timestamps with a Timestamp Query API or not.
  39138. *
  39139. * @type {boolean}
  39140. * @default false
  39141. */
  39142. this.trackTimestamp = ( parameters.trackTimestamp === true );
  39143. }
  39144. /**
  39145. * Initializes the backend so it is ready for usage. Concrete backends
  39146. * are supposed to implement their rendering context creation and related
  39147. * operations in this method.
  39148. *
  39149. * @async
  39150. * @param {Renderer} renderer - The renderer.
  39151. * @return {Promise} A Promise that resolves when the backend has been initialized.
  39152. */
  39153. async init( renderer ) {
  39154. this.renderer = renderer;
  39155. }
  39156. /**
  39157. * The coordinate system of the backend.
  39158. *
  39159. * @abstract
  39160. * @type {number}
  39161. * @readonly
  39162. */
  39163. get coordinateSystem() {}
  39164. // render context
  39165. /**
  39166. * This method is executed at the beginning of a render call and
  39167. * can be used by the backend to prepare the state for upcoming
  39168. * draw calls.
  39169. *
  39170. * @abstract
  39171. * @param {RenderContext} renderContext - The render context.
  39172. */
  39173. beginRender( /*renderContext*/ ) {}
  39174. /**
  39175. * This method is executed at the end of a render call and
  39176. * can be used by the backend to finalize work after draw
  39177. * calls.
  39178. *
  39179. * @abstract
  39180. * @param {RenderContext} renderContext - The render context.
  39181. */
  39182. finishRender( /*renderContext*/ ) {}
  39183. /**
  39184. * This method is executed at the beginning of a compute call and
  39185. * can be used by the backend to prepare the state for upcoming
  39186. * compute tasks.
  39187. *
  39188. * @abstract
  39189. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  39190. */
  39191. beginCompute( /*computeGroup*/ ) {}
  39192. /**
  39193. * This method is executed at the end of a compute call and
  39194. * can be used by the backend to finalize work after compute
  39195. * tasks.
  39196. *
  39197. * @abstract
  39198. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  39199. */
  39200. finishCompute( /*computeGroup*/ ) {}
  39201. // render object
  39202. /**
  39203. * Executes a draw command for the given render object.
  39204. *
  39205. * @abstract
  39206. * @param {RenderObject} renderObject - The render object to draw.
  39207. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  39208. */
  39209. draw( /*renderObject, info*/ ) { }
  39210. // compute node
  39211. /**
  39212. * Executes a compute command for the given compute node.
  39213. *
  39214. * @abstract
  39215. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  39216. * @param {Node} computeNode - The compute node.
  39217. * @param {Array<BindGroup>} bindings - The bindings.
  39218. * @param {ComputePipeline} computePipeline - The compute pipeline.
  39219. */
  39220. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  39221. // program
  39222. /**
  39223. * Creates a shader program from the given programmable stage.
  39224. *
  39225. * @abstract
  39226. * @param {ProgrammableStage} program - The programmable stage.
  39227. */
  39228. createProgram( /*program*/ ) { }
  39229. /**
  39230. * Destroys the shader program of the given programmable stage.
  39231. *
  39232. * @abstract
  39233. * @param {ProgrammableStage} program - The programmable stage.
  39234. */
  39235. destroyProgram( /*program*/ ) { }
  39236. // bindings
  39237. /**
  39238. * Creates bindings from the given bind group definition.
  39239. *
  39240. * @abstract
  39241. * @param {BindGroup} bindGroup - The bind group.
  39242. * @param {Array<BindGroup>} bindings - Array of bind groups.
  39243. * @param {number} cacheIndex - The cache index.
  39244. * @param {number} version - The version.
  39245. */
  39246. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  39247. /**
  39248. * Updates the given bind group definition.
  39249. *
  39250. * @abstract
  39251. * @param {BindGroup} bindGroup - The bind group.
  39252. * @param {Array<BindGroup>} bindings - Array of bind groups.
  39253. * @param {number} cacheIndex - The cache index.
  39254. * @param {number} version - The version.
  39255. */
  39256. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  39257. /**
  39258. * Updates a buffer binding.
  39259. *
  39260. * @abstract
  39261. * @param {Buffer} binding - The buffer binding to update.
  39262. */
  39263. updateBinding( /*binding*/ ) { }
  39264. // pipeline
  39265. /**
  39266. * Creates a render pipeline for the given render object.
  39267. *
  39268. * @abstract
  39269. * @param {RenderObject} renderObject - The render object.
  39270. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  39271. */
  39272. createRenderPipeline( /*renderObject, promises*/ ) { }
  39273. /**
  39274. * Creates a compute pipeline for the given compute node.
  39275. *
  39276. * @abstract
  39277. * @param {ComputePipeline} computePipeline - The compute pipeline.
  39278. * @param {Array<BindGroup>} bindings - The bindings.
  39279. */
  39280. createComputePipeline( /*computePipeline, bindings*/ ) { }
  39281. // cache key
  39282. /**
  39283. * Returns `true` if the render pipeline requires an update.
  39284. *
  39285. * @abstract
  39286. * @param {RenderObject} renderObject - The render object.
  39287. * @return {boolean} Whether the render pipeline requires an update or not.
  39288. */
  39289. needsRenderUpdate( /*renderObject*/ ) { }
  39290. /**
  39291. * Returns a cache key that is used to identify render pipelines.
  39292. *
  39293. * @abstract
  39294. * @param {RenderObject} renderObject - The render object.
  39295. * @return {string} The cache key.
  39296. */
  39297. getRenderCacheKey( /*renderObject*/ ) { }
  39298. // node builder
  39299. /**
  39300. * Returns a node builder for the given render object.
  39301. *
  39302. * @abstract
  39303. * @param {RenderObject} renderObject - The render object.
  39304. * @param {Renderer} renderer - The renderer.
  39305. * @return {NodeBuilder} The node builder.
  39306. */
  39307. createNodeBuilder( /*renderObject, renderer*/ ) { }
  39308. // textures
  39309. /**
  39310. * Creates a GPU sampler for the given texture.
  39311. *
  39312. * @abstract
  39313. * @param {Texture} texture - The texture to create the sampler for.
  39314. */
  39315. createSampler( /*texture*/ ) { }
  39316. /**
  39317. * Destroys the GPU sampler for the given texture.
  39318. *
  39319. * @abstract
  39320. * @param {Texture} texture - The texture to destroy the sampler for.
  39321. */
  39322. destroySampler( /*texture*/ ) {}
  39323. /**
  39324. * Creates a default texture for the given texture that can be used
  39325. * as a placeholder until the actual texture is ready for usage.
  39326. *
  39327. * @abstract
  39328. * @param {Texture} texture - The texture to create a default texture for.
  39329. */
  39330. createDefaultTexture( /*texture*/ ) { }
  39331. /**
  39332. * Defines a texture on the GPU for the given texture object.
  39333. *
  39334. * @abstract
  39335. * @param {Texture} texture - The texture.
  39336. * @param {Object} [options={}] - Optional configuration parameter.
  39337. */
  39338. createTexture( /*texture, options={}*/ ) { }
  39339. /**
  39340. * Uploads the updated texture data to the GPU.
  39341. *
  39342. * @abstract
  39343. * @param {Texture} texture - The texture.
  39344. * @param {Object} [options={}] - Optional configuration parameter.
  39345. */
  39346. updateTexture( /*texture, options = {}*/ ) { }
  39347. /**
  39348. * Generates mipmaps for the given texture.
  39349. *
  39350. * @abstract
  39351. * @param {Texture} texture - The texture.
  39352. */
  39353. generateMipmaps( /*texture*/ ) { }
  39354. /**
  39355. * Destroys the GPU data for the given texture object.
  39356. *
  39357. * @abstract
  39358. * @param {Texture} texture - The texture.
  39359. */
  39360. destroyTexture( /*texture*/ ) { }
  39361. /**
  39362. * Returns texture data as a typed array.
  39363. *
  39364. * @abstract
  39365. * @async
  39366. * @param {Texture} texture - The texture to copy.
  39367. * @param {number} x - The x coordinate of the copy origin.
  39368. * @param {number} y - The y coordinate of the copy origin.
  39369. * @param {number} width - The width of the copy.
  39370. * @param {number} height - The height of the copy.
  39371. * @param {number} faceIndex - The face index.
  39372. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  39373. */
  39374. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  39375. /**
  39376. * Copies data of the given source texture to the given destination texture.
  39377. *
  39378. * @abstract
  39379. * @param {Texture} srcTexture - The source texture.
  39380. * @param {Texture} dstTexture - The destination texture.
  39381. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  39382. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  39383. * @param {number} [srcLevel=0] - The source mip level to copy from.
  39384. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  39385. */
  39386. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  39387. /**
  39388. * Copies the current bound framebuffer to the given texture.
  39389. *
  39390. * @abstract
  39391. * @param {Texture} texture - The destination texture.
  39392. * @param {RenderContext} renderContext - The render context.
  39393. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  39394. */
  39395. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  39396. // attributes
  39397. /**
  39398. * Creates the GPU buffer of a shader attribute.
  39399. *
  39400. * @abstract
  39401. * @param {BufferAttribute} attribute - The buffer attribute.
  39402. */
  39403. createAttribute( /*attribute*/ ) { }
  39404. /**
  39405. * Creates the GPU buffer of an indexed shader attribute.
  39406. *
  39407. * @abstract
  39408. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  39409. */
  39410. createIndexAttribute( /*attribute*/ ) { }
  39411. /**
  39412. * Creates the GPU buffer of a storage attribute.
  39413. *
  39414. * @abstract
  39415. * @param {BufferAttribute} attribute - The buffer attribute.
  39416. */
  39417. createStorageAttribute( /*attribute*/ ) { }
  39418. /**
  39419. * Updates the GPU buffer of a shader attribute.
  39420. *
  39421. * @abstract
  39422. * @param {BufferAttribute} attribute - The buffer attribute to update.
  39423. */
  39424. updateAttribute( /*attribute*/ ) { }
  39425. /**
  39426. * Destroys the GPU buffer of a shader attribute.
  39427. *
  39428. * @abstract
  39429. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  39430. */
  39431. destroyAttribute( /*attribute*/ ) { }
  39432. // canvas
  39433. /**
  39434. * Returns the backend's rendering context.
  39435. *
  39436. * @abstract
  39437. * @return {Object} The rendering context.
  39438. */
  39439. getContext() { }
  39440. /**
  39441. * Backends can use this method if they have to run
  39442. * logic when the renderer gets resized.
  39443. *
  39444. * @abstract
  39445. */
  39446. updateSize() { }
  39447. /**
  39448. * Updates the viewport with the values from the given render context.
  39449. *
  39450. * @abstract
  39451. * @param {RenderContext} renderContext - The render context.
  39452. */
  39453. updateViewport( /*renderContext*/ ) {}
  39454. // utils
  39455. /**
  39456. * Returns `true` if the given 3D object is fully occluded by other
  39457. * 3D objects in the scene. Backends must implement this method by using
  39458. * a Occlusion Query API.
  39459. *
  39460. * @abstract
  39461. * @param {RenderContext} renderContext - The render context.
  39462. * @param {Object3D} object - The 3D object to test.
  39463. * @return {boolean} Whether the 3D object is fully occluded or not.
  39464. */
  39465. isOccluded( /*renderContext, object*/ ) {}
  39466. /**
  39467. * Resolves the time stamp for the given render context and type.
  39468. *
  39469. * @async
  39470. * @abstract
  39471. * @param {string} [type='render'] - The type of the time stamp.
  39472. * @return {Promise<number>} A Promise that resolves with the time stamp.
  39473. */
  39474. async resolveTimestampsAsync( type = 'render' ) {
  39475. if ( ! this.trackTimestamp ) {
  39476. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  39477. return;
  39478. }
  39479. const queryPool = this.timestampQueryPool[ type ];
  39480. if ( ! queryPool ) {
  39481. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  39482. return;
  39483. }
  39484. const duration = await queryPool.resolveQueriesAsync();
  39485. this.renderer.info[ type ].timestamp = duration;
  39486. return duration;
  39487. }
  39488. /**
  39489. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  39490. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  39491. *
  39492. * @async
  39493. * @abstract
  39494. * @return {Promise} A Promise that resolves when synchronization has been finished.
  39495. */
  39496. async waitForGPU() {}
  39497. /**
  39498. * This method performs a readback operation by moving buffer data from
  39499. * a storage buffer attribute from the GPU to the CPU.
  39500. *
  39501. * @async
  39502. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39503. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39504. */
  39505. async getArrayBufferAsync( /* attribute */ ) {}
  39506. /**
  39507. * Checks if the given feature is supported by the backend.
  39508. *
  39509. * @async
  39510. * @abstract
  39511. * @param {string} name - The feature's name.
  39512. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  39513. */
  39514. async hasFeatureAsync( /*name*/ ) { }
  39515. /**
  39516. * Checks if the given feature is supported by the backend.
  39517. *
  39518. * @abstract
  39519. * @param {string} name - The feature's name.
  39520. * @return {boolean} Whether the feature is supported or not.
  39521. */
  39522. hasFeature( /*name*/ ) {}
  39523. /**
  39524. * Returns the maximum anisotropy texture filtering value.
  39525. *
  39526. * @abstract
  39527. * @return {number} The maximum anisotropy texture filtering value.
  39528. */
  39529. getMaxAnisotropy() {}
  39530. /**
  39531. * Returns the drawing buffer size.
  39532. *
  39533. * @return {Vector2} The drawing buffer size.
  39534. */
  39535. getDrawingBufferSize() {
  39536. _vector2 = _vector2 || new Vector2();
  39537. return this.renderer.getDrawingBufferSize( _vector2 );
  39538. }
  39539. /**
  39540. * Defines the scissor test.
  39541. *
  39542. * @abstract
  39543. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39544. */
  39545. setScissorTest( /*boolean*/ ) { }
  39546. /**
  39547. * Returns the clear color and alpha into a single
  39548. * color object.
  39549. *
  39550. * @return {Color4} The clear color.
  39551. */
  39552. getClearColor() {
  39553. const renderer = this.renderer;
  39554. _color4 = _color4 || new Color4();
  39555. renderer.getClearColor( _color4 );
  39556. _color4.getRGB( _color4 );
  39557. return _color4;
  39558. }
  39559. /**
  39560. * Returns the DOM element. If no DOM element exists, the backend
  39561. * creates a new one.
  39562. *
  39563. * @return {HTMLCanvasElement} The DOM element.
  39564. */
  39565. getDomElement() {
  39566. let domElement = this.domElement;
  39567. if ( domElement === null ) {
  39568. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39569. // OffscreenCanvas does not have setAttribute, see #22811
  39570. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39571. this.domElement = domElement;
  39572. }
  39573. return domElement;
  39574. }
  39575. /**
  39576. * Sets a dictionary for the given object into the
  39577. * internal data structure.
  39578. *
  39579. * @param {Object} object - The object.
  39580. * @param {Object} value - The dictionary to set.
  39581. */
  39582. set( object, value ) {
  39583. this.data.set( object, value );
  39584. }
  39585. /**
  39586. * Returns the dictionary for the given object.
  39587. *
  39588. * @param {Object} object - The object.
  39589. * @return {Object} The object's dictionary.
  39590. */
  39591. get( object ) {
  39592. let map = this.data.get( object );
  39593. if ( map === undefined ) {
  39594. map = {};
  39595. this.data.set( object, map );
  39596. }
  39597. return map;
  39598. }
  39599. /**
  39600. * Checks if the given object has a dictionary
  39601. * with data defined.
  39602. *
  39603. * @param {Object} object - The object.
  39604. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  39605. */
  39606. has( object ) {
  39607. return this.data.has( object );
  39608. }
  39609. /**
  39610. * Deletes an object from the internal data structure.
  39611. *
  39612. * @param {Object} object - The object to delete.
  39613. */
  39614. delete( object ) {
  39615. this.data.delete( object );
  39616. }
  39617. /**
  39618. * Frees internal resources.
  39619. *
  39620. * @abstract
  39621. */
  39622. dispose() { }
  39623. }
  39624. let _id$1 = 0;
  39625. /**
  39626. * This module is internally used in context of compute shaders.
  39627. * This type of shader is not natively supported in WebGL 2 and
  39628. * thus implemented via Transform Feedback. `DualAttributeData`
  39629. * manages the related data.
  39630. *
  39631. * @private
  39632. */
  39633. class DualAttributeData {
  39634. constructor( attributeData, dualBuffer ) {
  39635. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39636. this.type = attributeData.type;
  39637. this.bufferType = attributeData.bufferType;
  39638. this.pbo = attributeData.pbo;
  39639. this.byteLength = attributeData.byteLength;
  39640. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39641. this.version = attributeData.version;
  39642. this.isInteger = attributeData.isInteger;
  39643. this.activeBufferIndex = 0;
  39644. this.baseId = attributeData.id;
  39645. }
  39646. get id() {
  39647. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39648. }
  39649. get bufferGPU() {
  39650. return this.buffers[ this.activeBufferIndex ];
  39651. }
  39652. get transformBuffer() {
  39653. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39654. }
  39655. switchBuffers() {
  39656. this.activeBufferIndex ^= 1;
  39657. }
  39658. }
  39659. /**
  39660. * A WebGL 2 backend utility module for managing shader attributes.
  39661. *
  39662. * @private
  39663. */
  39664. class WebGLAttributeUtils {
  39665. /**
  39666. * Constructs a new utility object.
  39667. *
  39668. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39669. */
  39670. constructor( backend ) {
  39671. /**
  39672. * A reference to the WebGL 2 backend.
  39673. *
  39674. * @type {WebGLBackend}
  39675. */
  39676. this.backend = backend;
  39677. }
  39678. /**
  39679. * Creates the GPU buffer for the given buffer attribute.
  39680. *
  39681. * @param {BufferAttribute} attribute - The buffer attribute.
  39682. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  39683. */
  39684. createAttribute( attribute, bufferType ) {
  39685. const backend = this.backend;
  39686. const { gl } = backend;
  39687. const array = attribute.array;
  39688. const usage = attribute.usage || gl.STATIC_DRAW;
  39689. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39690. const bufferData = backend.get( bufferAttribute );
  39691. let bufferGPU = bufferData.bufferGPU;
  39692. if ( bufferGPU === undefined ) {
  39693. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39694. bufferData.bufferGPU = bufferGPU;
  39695. bufferData.bufferType = bufferType;
  39696. bufferData.version = bufferAttribute.version;
  39697. }
  39698. //attribute.onUploadCallback();
  39699. let type;
  39700. if ( array instanceof Float32Array ) {
  39701. type = gl.FLOAT;
  39702. } else if ( array instanceof Uint16Array ) {
  39703. if ( attribute.isFloat16BufferAttribute ) {
  39704. type = gl.HALF_FLOAT;
  39705. } else {
  39706. type = gl.UNSIGNED_SHORT;
  39707. }
  39708. } else if ( array instanceof Int16Array ) {
  39709. type = gl.SHORT;
  39710. } else if ( array instanceof Uint32Array ) {
  39711. type = gl.UNSIGNED_INT;
  39712. } else if ( array instanceof Int32Array ) {
  39713. type = gl.INT;
  39714. } else if ( array instanceof Int8Array ) {
  39715. type = gl.BYTE;
  39716. } else if ( array instanceof Uint8Array ) {
  39717. type = gl.UNSIGNED_BYTE;
  39718. } else if ( array instanceof Uint8ClampedArray ) {
  39719. type = gl.UNSIGNED_BYTE;
  39720. } else {
  39721. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39722. }
  39723. let attributeData = {
  39724. bufferGPU,
  39725. bufferType,
  39726. type,
  39727. byteLength: array.byteLength,
  39728. bytesPerElement: array.BYTES_PER_ELEMENT,
  39729. version: attribute.version,
  39730. pbo: attribute.pbo,
  39731. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39732. id: _id$1 ++
  39733. };
  39734. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39735. // create buffer for transform feedback use
  39736. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39737. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39738. }
  39739. backend.set( attribute, attributeData );
  39740. }
  39741. /**
  39742. * Updates the GPU buffer of the given buffer attribute.
  39743. *
  39744. * @param {BufferAttribute} attribute - The buffer attribute.
  39745. */
  39746. updateAttribute( attribute ) {
  39747. const backend = this.backend;
  39748. const { gl } = backend;
  39749. const array = attribute.array;
  39750. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39751. const bufferData = backend.get( bufferAttribute );
  39752. const bufferType = bufferData.bufferType;
  39753. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39754. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39755. if ( updateRanges.length === 0 ) {
  39756. // Not using update ranges
  39757. gl.bufferSubData( bufferType, 0, array );
  39758. } else {
  39759. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39760. const range = updateRanges[ i ];
  39761. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39762. array, range.start, range.count );
  39763. }
  39764. bufferAttribute.clearUpdateRanges();
  39765. }
  39766. gl.bindBuffer( bufferType, null );
  39767. bufferData.version = bufferAttribute.version;
  39768. }
  39769. /**
  39770. * Destroys the GPU buffer of the given buffer attribute.
  39771. *
  39772. * @param {BufferAttribute} attribute - The buffer attribute.
  39773. */
  39774. destroyAttribute( attribute ) {
  39775. const backend = this.backend;
  39776. const { gl } = backend;
  39777. if ( attribute.isInterleavedBufferAttribute ) {
  39778. backend.delete( attribute.data );
  39779. }
  39780. const attributeData = backend.get( attribute );
  39781. gl.deleteBuffer( attributeData.bufferGPU );
  39782. backend.delete( attribute );
  39783. }
  39784. /**
  39785. * This method performs a readback operation by moving buffer data from
  39786. * a storage buffer attribute from the GPU to the CPU.
  39787. *
  39788. * @async
  39789. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39790. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39791. */
  39792. async getArrayBufferAsync( attribute ) {
  39793. const backend = this.backend;
  39794. const { gl } = backend;
  39795. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39796. const { bufferGPU } = backend.get( bufferAttribute );
  39797. const array = attribute.array;
  39798. const byteLength = array.byteLength;
  39799. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39800. const writeBuffer = gl.createBuffer();
  39801. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39802. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39803. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39804. await backend.utils._clientWaitAsync();
  39805. const dstBuffer = new attribute.array.constructor( array.length );
  39806. // Ensure the buffer is bound before reading
  39807. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39808. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39809. gl.deleteBuffer( writeBuffer );
  39810. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39811. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39812. return dstBuffer.buffer;
  39813. }
  39814. /**
  39815. * Creates a WebGL buffer with the given data.
  39816. *
  39817. * @private
  39818. * @param {WebGL2RenderingContext} gl - The rendering context.
  39819. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  39820. * @param {TypedArray} array - The array of the buffer attribute.
  39821. * @param {GLenum} usage - The usage.
  39822. * @return {WebGLBuffer} The WebGL buffer.
  39823. */
  39824. _createBuffer( gl, bufferType, array, usage ) {
  39825. const bufferGPU = gl.createBuffer();
  39826. gl.bindBuffer( bufferType, bufferGPU );
  39827. gl.bufferData( bufferType, array, usage );
  39828. gl.bindBuffer( bufferType, null );
  39829. return bufferGPU;
  39830. }
  39831. }
  39832. let equationToGL, factorToGL;
  39833. /**
  39834. * A WebGL 2 backend utility module for managing the WebGL state.
  39835. *
  39836. * The major goal of this module is to reduce the number of state changes
  39837. * by caching the WEbGL state with a series of variables. In this way, the
  39838. * renderer only executes state change commands when necessary which
  39839. * improves the overall performance.
  39840. *
  39841. * @private
  39842. */
  39843. class WebGLState {
  39844. /**
  39845. * Constructs a new utility object.
  39846. *
  39847. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39848. */
  39849. constructor( backend ) {
  39850. /**
  39851. * A reference to the WebGL 2 backend.
  39852. *
  39853. * @type {WebGLBackend}
  39854. */
  39855. this.backend = backend;
  39856. /**
  39857. * A reference to the rendering context.
  39858. *
  39859. * @type {WebGL2RenderingContext}
  39860. */
  39861. this.gl = this.backend.gl;
  39862. // Below properties are intended to cache
  39863. // the WebGL state and are not explicitly
  39864. // documented for convenience reasons.
  39865. this.enabled = {};
  39866. this.currentFlipSided = null;
  39867. this.currentCullFace = null;
  39868. this.currentProgram = null;
  39869. this.currentBlendingEnabled = false;
  39870. this.currentBlending = null;
  39871. this.currentBlendSrc = null;
  39872. this.currentBlendDst = null;
  39873. this.currentBlendSrcAlpha = null;
  39874. this.currentBlendDstAlpha = null;
  39875. this.currentPremultipledAlpha = null;
  39876. this.currentPolygonOffsetFactor = null;
  39877. this.currentPolygonOffsetUnits = null;
  39878. this.currentColorMask = null;
  39879. this.currentDepthFunc = null;
  39880. this.currentDepthMask = null;
  39881. this.currentStencilFunc = null;
  39882. this.currentStencilRef = null;
  39883. this.currentStencilFuncMask = null;
  39884. this.currentStencilFail = null;
  39885. this.currentStencilZFail = null;
  39886. this.currentStencilZPass = null;
  39887. this.currentStencilMask = null;
  39888. this.currentLineWidth = null;
  39889. this.currentClippingPlanes = 0;
  39890. this.currentVAO = null;
  39891. this.currentIndex = null;
  39892. this.currentBoundFramebuffers = {};
  39893. this.currentDrawbuffers = new WeakMap();
  39894. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39895. this.currentTextureSlot = null;
  39896. this.currentBoundTextures = {};
  39897. this.currentBoundBufferBases = {};
  39898. this._init();
  39899. }
  39900. /**
  39901. * Inits the state of the utility.
  39902. *
  39903. * @private
  39904. */
  39905. _init() {
  39906. const gl = this.gl;
  39907. // Store only WebGL constants here.
  39908. equationToGL = {
  39909. [ AddEquation ]: gl.FUNC_ADD,
  39910. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39911. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39912. };
  39913. factorToGL = {
  39914. [ ZeroFactor ]: gl.ZERO,
  39915. [ OneFactor ]: gl.ONE,
  39916. [ SrcColorFactor ]: gl.SRC_COLOR,
  39917. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39918. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39919. [ DstColorFactor ]: gl.DST_COLOR,
  39920. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39921. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39922. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39923. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39924. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39925. };
  39926. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  39927. const viewportParam = gl.getParameter( gl.VIEWPORT );
  39928. this.currentScissor = new Vector4().fromArray( scissorParam );
  39929. this.currentViewport = new Vector4().fromArray( viewportParam );
  39930. this._tempVec4 = new Vector4();
  39931. }
  39932. /**
  39933. * Enables the given WebGL capability.
  39934. *
  39935. * This method caches the capability state so
  39936. * `gl.enable()` is only called when necessary.
  39937. *
  39938. * @param {GLenum} id - The capability to enable.
  39939. */
  39940. enable( id ) {
  39941. const { enabled } = this;
  39942. if ( enabled[ id ] !== true ) {
  39943. this.gl.enable( id );
  39944. enabled[ id ] = true;
  39945. }
  39946. }
  39947. /**
  39948. * Disables the given WebGL capability.
  39949. *
  39950. * This method caches the capability state so
  39951. * `gl.disable()` is only called when necessary.
  39952. *
  39953. * @param {GLenum} id - The capability to enable.
  39954. */
  39955. disable( id ) {
  39956. const { enabled } = this;
  39957. if ( enabled[ id ] !== false ) {
  39958. this.gl.disable( id );
  39959. enabled[ id ] = false;
  39960. }
  39961. }
  39962. /**
  39963. * Specifies whether polygons are front- or back-facing
  39964. * by setting the winding orientation.
  39965. *
  39966. * This method caches the state so `gl.frontFace()` is only
  39967. * called when necessary.
  39968. *
  39969. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  39970. */
  39971. setFlipSided( flipSided ) {
  39972. if ( this.currentFlipSided !== flipSided ) {
  39973. const { gl } = this;
  39974. if ( flipSided ) {
  39975. gl.frontFace( gl.CW );
  39976. } else {
  39977. gl.frontFace( gl.CCW );
  39978. }
  39979. this.currentFlipSided = flipSided;
  39980. }
  39981. }
  39982. /**
  39983. * Specifies whether or not front- and/or back-facing
  39984. * polygons can be culled.
  39985. *
  39986. * This method caches the state so `gl.cullFace()` is only
  39987. * called when necessary.
  39988. *
  39989. * @param {number} cullFace - Defines which polygons are candidates for culling.
  39990. */
  39991. setCullFace( cullFace ) {
  39992. const { gl } = this;
  39993. if ( cullFace !== CullFaceNone ) {
  39994. this.enable( gl.CULL_FACE );
  39995. if ( cullFace !== this.currentCullFace ) {
  39996. if ( cullFace === CullFaceBack ) {
  39997. gl.cullFace( gl.BACK );
  39998. } else if ( cullFace === CullFaceFront ) {
  39999. gl.cullFace( gl.FRONT );
  40000. } else {
  40001. gl.cullFace( gl.FRONT_AND_BACK );
  40002. }
  40003. }
  40004. } else {
  40005. this.disable( gl.CULL_FACE );
  40006. }
  40007. this.currentCullFace = cullFace;
  40008. }
  40009. /**
  40010. * Specifies the width of line primitives.
  40011. *
  40012. * This method caches the state so `gl.lineWidth()` is only
  40013. * called when necessary.
  40014. *
  40015. * @param {number} width - The line width.
  40016. */
  40017. setLineWidth( width ) {
  40018. const { currentLineWidth, gl } = this;
  40019. if ( width !== currentLineWidth ) {
  40020. gl.lineWidth( width );
  40021. this.currentLineWidth = width;
  40022. }
  40023. }
  40024. /**
  40025. * Defines the blending.
  40026. *
  40027. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  40028. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  40029. *
  40030. * @param {number} blending - The blending type.
  40031. * @param {number} blendEquation - The blending equation.
  40032. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  40033. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  40034. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  40035. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  40036. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  40037. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  40038. */
  40039. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  40040. const { gl } = this;
  40041. if ( blending === NoBlending ) {
  40042. if ( this.currentBlendingEnabled === true ) {
  40043. this.disable( gl.BLEND );
  40044. this.currentBlendingEnabled = false;
  40045. }
  40046. return;
  40047. }
  40048. if ( this.currentBlendingEnabled === false ) {
  40049. this.enable( gl.BLEND );
  40050. this.currentBlendingEnabled = true;
  40051. }
  40052. if ( blending !== CustomBlending ) {
  40053. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  40054. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  40055. gl.blendEquation( gl.FUNC_ADD );
  40056. this.currentBlendEquation = AddEquation;
  40057. this.currentBlendEquationAlpha = AddEquation;
  40058. }
  40059. if ( premultipliedAlpha ) {
  40060. switch ( blending ) {
  40061. case NormalBlending:
  40062. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40063. break;
  40064. case AdditiveBlending:
  40065. gl.blendFunc( gl.ONE, gl.ONE );
  40066. break;
  40067. case SubtractiveBlending:
  40068. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40069. break;
  40070. case MultiplyBlending:
  40071. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  40072. break;
  40073. default:
  40074. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40075. break;
  40076. }
  40077. } else {
  40078. switch ( blending ) {
  40079. case NormalBlending:
  40080. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40081. break;
  40082. case AdditiveBlending:
  40083. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  40084. break;
  40085. case SubtractiveBlending:
  40086. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40087. break;
  40088. case MultiplyBlending:
  40089. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  40090. break;
  40091. default:
  40092. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40093. break;
  40094. }
  40095. }
  40096. this.currentBlendSrc = null;
  40097. this.currentBlendDst = null;
  40098. this.currentBlendSrcAlpha = null;
  40099. this.currentBlendDstAlpha = null;
  40100. this.currentBlending = blending;
  40101. this.currentPremultipledAlpha = premultipliedAlpha;
  40102. }
  40103. return;
  40104. }
  40105. // custom blending
  40106. blendEquationAlpha = blendEquationAlpha || blendEquation;
  40107. blendSrcAlpha = blendSrcAlpha || blendSrc;
  40108. blendDstAlpha = blendDstAlpha || blendDst;
  40109. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  40110. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  40111. this.currentBlendEquation = blendEquation;
  40112. this.currentBlendEquationAlpha = blendEquationAlpha;
  40113. }
  40114. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  40115. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  40116. this.currentBlendSrc = blendSrc;
  40117. this.currentBlendDst = blendDst;
  40118. this.currentBlendSrcAlpha = blendSrcAlpha;
  40119. this.currentBlendDstAlpha = blendDstAlpha;
  40120. }
  40121. this.currentBlending = blending;
  40122. this.currentPremultipledAlpha = false;
  40123. }
  40124. /**
  40125. * Specifies whether colors can be written when rendering
  40126. * into a framebuffer or not.
  40127. *
  40128. * This method caches the state so `gl.colorMask()` is only
  40129. * called when necessary.
  40130. *
  40131. * @param {boolean} colorMask - The color mask.
  40132. */
  40133. setColorMask( colorMask ) {
  40134. if ( this.currentColorMask !== colorMask ) {
  40135. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  40136. this.currentColorMask = colorMask;
  40137. }
  40138. }
  40139. /**
  40140. * Specifies whether the depth test is enabled or not.
  40141. *
  40142. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  40143. */
  40144. setDepthTest( depthTest ) {
  40145. const { gl } = this;
  40146. if ( depthTest ) {
  40147. this.enable( gl.DEPTH_TEST );
  40148. } else {
  40149. this.disable( gl.DEPTH_TEST );
  40150. }
  40151. }
  40152. /**
  40153. * Specifies whether depth values can be written when rendering
  40154. * into a framebuffer or not.
  40155. *
  40156. * This method caches the state so `gl.depthMask()` is only
  40157. * called when necessary.
  40158. *
  40159. * @param {boolean} depthMask - The depth mask.
  40160. */
  40161. setDepthMask( depthMask ) {
  40162. if ( this.currentDepthMask !== depthMask ) {
  40163. this.gl.depthMask( depthMask );
  40164. this.currentDepthMask = depthMask;
  40165. }
  40166. }
  40167. /**
  40168. * Specifies the depth compare function.
  40169. *
  40170. * This method caches the state so `gl.depthFunc()` is only
  40171. * called when necessary.
  40172. *
  40173. * @param {number} depthFunc - The depth compare function.
  40174. */
  40175. setDepthFunc( depthFunc ) {
  40176. if ( this.currentDepthFunc !== depthFunc ) {
  40177. const { gl } = this;
  40178. switch ( depthFunc ) {
  40179. case NeverDepth:
  40180. gl.depthFunc( gl.NEVER );
  40181. break;
  40182. case AlwaysDepth:
  40183. gl.depthFunc( gl.ALWAYS );
  40184. break;
  40185. case LessDepth:
  40186. gl.depthFunc( gl.LESS );
  40187. break;
  40188. case LessEqualDepth:
  40189. gl.depthFunc( gl.LEQUAL );
  40190. break;
  40191. case EqualDepth:
  40192. gl.depthFunc( gl.EQUAL );
  40193. break;
  40194. case GreaterEqualDepth:
  40195. gl.depthFunc( gl.GEQUAL );
  40196. break;
  40197. case GreaterDepth:
  40198. gl.depthFunc( gl.GREATER );
  40199. break;
  40200. case NotEqualDepth:
  40201. gl.depthFunc( gl.NOTEQUAL );
  40202. break;
  40203. default:
  40204. gl.depthFunc( gl.LEQUAL );
  40205. }
  40206. this.currentDepthFunc = depthFunc;
  40207. }
  40208. }
  40209. /**
  40210. * Specifies the scissor box.
  40211. *
  40212. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  40213. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  40214. * @param {number} width - The width of the viewport.
  40215. * @param {number} height - The height of the viewport.
  40216. *
  40217. */
  40218. scissor( x, y, width, height ) {
  40219. const scissor = this._tempVec4.set( x, y, width, height );
  40220. if ( this.currentScissor.equals( scissor ) === false ) {
  40221. const { gl } = this;
  40222. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  40223. this.currentScissor.copy( scissor );
  40224. }
  40225. }
  40226. /**
  40227. * Specifies the viewport.
  40228. *
  40229. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  40230. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  40231. * @param {number} width - The width of the viewport.
  40232. * @param {number} height - The height of the viewport.
  40233. *
  40234. */
  40235. viewport( x, y, width, height ) {
  40236. const viewport = this._tempVec4.set( x, y, width, height );
  40237. if ( this.currentViewport.equals( viewport ) === false ) {
  40238. const { gl } = this;
  40239. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  40240. this.currentViewport.copy( viewport );
  40241. }
  40242. }
  40243. /**
  40244. * Defines the scissor test.
  40245. *
  40246. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40247. */
  40248. setScissorTest( boolean ) {
  40249. const gl = this.gl;
  40250. if ( boolean ) {
  40251. gl.enable( gl.SCISSOR_TEST );
  40252. } else {
  40253. gl.disable( gl.SCISSOR_TEST );
  40254. }
  40255. }
  40256. /**
  40257. * Specifies whether the stencil test is enabled or not.
  40258. *
  40259. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  40260. */
  40261. setStencilTest( stencilTest ) {
  40262. const { gl } = this;
  40263. if ( stencilTest ) {
  40264. this.enable( gl.STENCIL_TEST );
  40265. } else {
  40266. this.disable( gl.STENCIL_TEST );
  40267. }
  40268. }
  40269. /**
  40270. * Specifies whether stencil values can be written when rendering
  40271. * into a framebuffer or not.
  40272. *
  40273. * This method caches the state so `gl.stencilMask()` is only
  40274. * called when necessary.
  40275. *
  40276. * @param {boolean} stencilMask - The stencil mask.
  40277. */
  40278. setStencilMask( stencilMask ) {
  40279. if ( this.currentStencilMask !== stencilMask ) {
  40280. this.gl.stencilMask( stencilMask );
  40281. this.currentStencilMask = stencilMask;
  40282. }
  40283. }
  40284. /**
  40285. * Specifies whether the stencil test functions.
  40286. *
  40287. * This method caches the state so `gl.stencilFunc()` is only
  40288. * called when necessary.
  40289. *
  40290. * @param {number} stencilFunc - The stencil compare function.
  40291. * @param {number} stencilRef - The reference value for the stencil test.
  40292. * @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.
  40293. */
  40294. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  40295. if ( this.currentStencilFunc !== stencilFunc ||
  40296. this.currentStencilRef !== stencilRef ||
  40297. this.currentStencilFuncMask !== stencilMask ) {
  40298. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  40299. this.currentStencilFunc = stencilFunc;
  40300. this.currentStencilRef = stencilRef;
  40301. this.currentStencilFuncMask = stencilMask;
  40302. }
  40303. }
  40304. /**
  40305. * Specifies whether the stencil test operation.
  40306. *
  40307. * This method caches the state so `gl.stencilOp()` is only
  40308. * called when necessary.
  40309. *
  40310. * @param {number} stencilFail - The function to use when the stencil test fails.
  40311. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  40312. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  40313. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  40314. */
  40315. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  40316. if ( this.currentStencilFail !== stencilFail ||
  40317. this.currentStencilZFail !== stencilZFail ||
  40318. this.currentStencilZPass !== stencilZPass ) {
  40319. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  40320. this.currentStencilFail = stencilFail;
  40321. this.currentStencilZFail = stencilZFail;
  40322. this.currentStencilZPass = stencilZPass;
  40323. }
  40324. }
  40325. /**
  40326. * Configures the WebGL state for the given material.
  40327. *
  40328. * @param {Material} material - The material to configure the state for.
  40329. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  40330. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  40331. */
  40332. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  40333. const { gl } = this;
  40334. material.side === DoubleSide
  40335. ? this.disable( gl.CULL_FACE )
  40336. : this.enable( gl.CULL_FACE );
  40337. let flipSided = ( material.side === BackSide );
  40338. if ( frontFaceCW ) flipSided = ! flipSided;
  40339. this.setFlipSided( flipSided );
  40340. ( material.blending === NormalBlending && material.transparent === false )
  40341. ? this.setBlending( NoBlending )
  40342. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  40343. this.setDepthFunc( material.depthFunc );
  40344. this.setDepthTest( material.depthTest );
  40345. this.setDepthMask( material.depthWrite );
  40346. this.setColorMask( material.colorWrite );
  40347. const stencilWrite = material.stencilWrite;
  40348. this.setStencilTest( stencilWrite );
  40349. if ( stencilWrite ) {
  40350. this.setStencilMask( material.stencilWriteMask );
  40351. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  40352. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  40353. }
  40354. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  40355. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  40356. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  40357. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  40358. if ( hardwareClippingPlanes > 0 ) {
  40359. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  40360. const CLIP_DISTANCE0_WEBGL = 0x3000;
  40361. for ( let i = 0; i < 8; i ++ ) {
  40362. if ( i < hardwareClippingPlanes ) {
  40363. this.enable( CLIP_DISTANCE0_WEBGL + i );
  40364. } else {
  40365. this.disable( CLIP_DISTANCE0_WEBGL + i );
  40366. }
  40367. }
  40368. }
  40369. }
  40370. }
  40371. /**
  40372. * Specifies the polygon offset.
  40373. *
  40374. * This method caches the state so `gl.polygonOffset()` is only
  40375. * called when necessary.
  40376. *
  40377. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  40378. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  40379. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  40380. */
  40381. setPolygonOffset( polygonOffset, factor, units ) {
  40382. const { gl } = this;
  40383. if ( polygonOffset ) {
  40384. this.enable( gl.POLYGON_OFFSET_FILL );
  40385. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  40386. gl.polygonOffset( factor, units );
  40387. this.currentPolygonOffsetFactor = factor;
  40388. this.currentPolygonOffsetUnits = units;
  40389. }
  40390. } else {
  40391. this.disable( gl.POLYGON_OFFSET_FILL );
  40392. }
  40393. }
  40394. /**
  40395. * Defines the usage of the given WebGL program.
  40396. *
  40397. * This method caches the state so `gl.useProgram()` is only
  40398. * called when necessary.
  40399. *
  40400. * @param {WebGLProgram} program - The WebGL program to use.
  40401. * @return {boolean} Whether a program change has been executed or not.
  40402. */
  40403. useProgram( program ) {
  40404. if ( this.currentProgram !== program ) {
  40405. this.gl.useProgram( program );
  40406. this.currentProgram = program;
  40407. return true;
  40408. }
  40409. return false;
  40410. }
  40411. /**
  40412. * Sets the vertex state by binding the given VAO and element buffer.
  40413. *
  40414. * @param {WebGLVertexArrayObject} vao - The VAO.
  40415. * @param {WebGLBuffer} indexBuffer - The index buffer.
  40416. * @return {boolean} Whether a vertex state has been changed or not.
  40417. */
  40418. setVertexState( vao, indexBuffer = null ) {
  40419. const gl = this.gl;
  40420. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  40421. gl.bindVertexArray( vao );
  40422. if ( indexBuffer !== null ) {
  40423. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  40424. }
  40425. this.currentVAO = vao;
  40426. this.currentIndex = indexBuffer;
  40427. return true;
  40428. }
  40429. return false;
  40430. }
  40431. /**
  40432. * Resets the vertex array state by resetting the VAO and element buffer.
  40433. */
  40434. resetVertexState() {
  40435. const gl = this.gl;
  40436. gl.bindVertexArray( null );
  40437. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  40438. this.currentVAO = null;
  40439. this.currentIndex = null;
  40440. }
  40441. // framebuffer
  40442. /**
  40443. * Binds the given framebuffer.
  40444. *
  40445. * This method caches the state so `gl.bindFramebuffer()` is only
  40446. * called when necessary.
  40447. *
  40448. * @param {number} target - The binding point (target).
  40449. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  40450. * @return {boolean} Whether a bind has been executed or not.
  40451. */
  40452. bindFramebuffer( target, framebuffer ) {
  40453. const { gl, currentBoundFramebuffers } = this;
  40454. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  40455. gl.bindFramebuffer( target, framebuffer );
  40456. currentBoundFramebuffers[ target ] = framebuffer;
  40457. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  40458. if ( target === gl.DRAW_FRAMEBUFFER ) {
  40459. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  40460. }
  40461. if ( target === gl.FRAMEBUFFER ) {
  40462. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  40463. }
  40464. return true;
  40465. }
  40466. return false;
  40467. }
  40468. /**
  40469. * Defines draw buffers to which fragment colors are written into.
  40470. * Configures the MRT setup of custom framebuffers.
  40471. *
  40472. * This method caches the state so `gl.drawBuffers()` is only
  40473. * called when necessary.
  40474. *
  40475. * @param {RenderContext} renderContext - The render context.
  40476. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  40477. */
  40478. drawBuffers( renderContext, framebuffer ) {
  40479. const { gl } = this;
  40480. let drawBuffers = [];
  40481. let needsUpdate = false;
  40482. if ( renderContext.textures !== null ) {
  40483. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  40484. if ( drawBuffers === undefined ) {
  40485. drawBuffers = [];
  40486. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  40487. }
  40488. const textures = renderContext.textures;
  40489. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  40490. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  40491. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  40492. }
  40493. drawBuffers.length = textures.length;
  40494. needsUpdate = true;
  40495. }
  40496. } else {
  40497. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  40498. drawBuffers[ 0 ] = gl.BACK;
  40499. needsUpdate = true;
  40500. }
  40501. }
  40502. if ( needsUpdate ) {
  40503. gl.drawBuffers( drawBuffers );
  40504. }
  40505. }
  40506. // texture
  40507. /**
  40508. * Makes the given texture unit active.
  40509. *
  40510. * This method caches the state so `gl.activeTexture()` is only
  40511. * called when necessary.
  40512. *
  40513. * @param {number} webglSlot - The texture unit to make active.
  40514. */
  40515. activeTexture( webglSlot ) {
  40516. const { gl, currentTextureSlot, maxTextures } = this;
  40517. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  40518. if ( currentTextureSlot !== webglSlot ) {
  40519. gl.activeTexture( webglSlot );
  40520. this.currentTextureSlot = webglSlot;
  40521. }
  40522. }
  40523. /**
  40524. * Binds the given WebGL texture to a target.
  40525. *
  40526. * This method caches the state so `gl.bindTexture()` is only
  40527. * called when necessary.
  40528. *
  40529. * @param {number} webglType - The binding point (target).
  40530. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  40531. * @param {number} webglSlot - The texture.
  40532. */
  40533. bindTexture( webglType, webglTexture, webglSlot ) {
  40534. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  40535. if ( webglSlot === undefined ) {
  40536. if ( currentTextureSlot === null ) {
  40537. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  40538. } else {
  40539. webglSlot = currentTextureSlot;
  40540. }
  40541. }
  40542. let boundTexture = currentBoundTextures[ webglSlot ];
  40543. if ( boundTexture === undefined ) {
  40544. boundTexture = { type: undefined, texture: undefined };
  40545. currentBoundTextures[ webglSlot ] = boundTexture;
  40546. }
  40547. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  40548. if ( currentTextureSlot !== webglSlot ) {
  40549. gl.activeTexture( webglSlot );
  40550. this.currentTextureSlot = webglSlot;
  40551. }
  40552. gl.bindTexture( webglType, webglTexture );
  40553. boundTexture.type = webglType;
  40554. boundTexture.texture = webglTexture;
  40555. }
  40556. }
  40557. /**
  40558. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  40559. *
  40560. * This method caches the state so `gl.bindBufferBase()` is only
  40561. * called when necessary.
  40562. *
  40563. * @param {number} target - The target for the bind operation.
  40564. * @param {number} index - The index of the target.
  40565. * @param {WebGLBuffer} buffer - The WebGL buffer.
  40566. * @return {boolean} Whether a bind has been executed or not.
  40567. */
  40568. bindBufferBase( target, index, buffer ) {
  40569. const { gl } = this;
  40570. const key = `${target}-${index}`;
  40571. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  40572. gl.bindBufferBase( target, index, buffer );
  40573. this.currentBoundBufferBases[ key ] = buffer;
  40574. return true;
  40575. }
  40576. return false;
  40577. }
  40578. /**
  40579. * Unbinds the current bound texture.
  40580. *
  40581. * This method caches the state so `gl.bindTexture()` is only
  40582. * called when necessary.
  40583. */
  40584. unbindTexture() {
  40585. const { gl, currentTextureSlot, currentBoundTextures } = this;
  40586. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  40587. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  40588. gl.bindTexture( boundTexture.type, null );
  40589. boundTexture.type = undefined;
  40590. boundTexture.texture = undefined;
  40591. }
  40592. }
  40593. }
  40594. /**
  40595. * A WebGL 2 backend utility module with common helpers.
  40596. *
  40597. * @private
  40598. */
  40599. class WebGLUtils {
  40600. /**
  40601. * Constructs a new utility object.
  40602. *
  40603. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40604. */
  40605. constructor( backend ) {
  40606. /**
  40607. * A reference to the WebGL 2 backend.
  40608. *
  40609. * @type {WebGLBackend}
  40610. */
  40611. this.backend = backend;
  40612. /**
  40613. * A reference to the rendering context.
  40614. *
  40615. * @type {WebGL2RenderingContext}
  40616. */
  40617. this.gl = this.backend.gl;
  40618. /**
  40619. * A reference to a backend module holding extension-related
  40620. * utility functions.
  40621. *
  40622. * @type {WebGLExtensions}
  40623. */
  40624. this.extensions = backend.extensions;
  40625. }
  40626. /**
  40627. * Converts the given three.js constant into a WebGL constant.
  40628. * The method currently supports the conversion of texture formats
  40629. * and types.
  40630. *
  40631. * @param {number} p - The three.js constant.
  40632. * @param {string} [colorSpace=NoColorSpace] - The color space.
  40633. * @return {?number} The corresponding WebGL constant.
  40634. */
  40635. convert( p, colorSpace = NoColorSpace ) {
  40636. const { gl, extensions } = this;
  40637. let extension;
  40638. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  40639. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  40640. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  40641. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  40642. if ( p === ByteType ) return gl.BYTE;
  40643. if ( p === ShortType ) return gl.SHORT;
  40644. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  40645. if ( p === IntType ) return gl.INT;
  40646. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  40647. if ( p === FloatType ) return gl.FLOAT;
  40648. if ( p === HalfFloatType ) {
  40649. return gl.HALF_FLOAT;
  40650. }
  40651. if ( p === AlphaFormat ) return gl.ALPHA;
  40652. if ( p === RGBFormat ) return gl.RGB;
  40653. if ( p === RGBAFormat ) return gl.RGBA;
  40654. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  40655. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  40656. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  40657. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  40658. // WebGL2 formats.
  40659. if ( p === RedFormat ) return gl.RED;
  40660. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  40661. if ( p === RGFormat ) return gl.RG;
  40662. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  40663. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  40664. // S3TC
  40665. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  40666. if ( colorSpace === SRGBColorSpace ) {
  40667. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  40668. if ( extension !== null ) {
  40669. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  40670. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  40671. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  40672. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  40673. } else {
  40674. return null;
  40675. }
  40676. } else {
  40677. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  40678. if ( extension !== null ) {
  40679. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  40680. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  40681. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  40682. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  40683. } else {
  40684. return null;
  40685. }
  40686. }
  40687. }
  40688. // PVRTC
  40689. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  40690. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  40691. if ( extension !== null ) {
  40692. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  40693. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  40694. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  40695. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  40696. } else {
  40697. return null;
  40698. }
  40699. }
  40700. // ETC
  40701. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  40702. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  40703. if ( extension !== null ) {
  40704. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  40705. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  40706. } else {
  40707. return null;
  40708. }
  40709. }
  40710. // ASTC
  40711. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  40712. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  40713. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  40714. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  40715. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  40716. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  40717. if ( extension !== null ) {
  40718. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  40719. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  40720. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  40721. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  40722. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  40723. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  40724. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  40725. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  40726. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  40727. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  40728. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  40729. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  40730. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  40731. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  40732. } else {
  40733. return null;
  40734. }
  40735. }
  40736. // BPTC
  40737. if ( p === RGBA_BPTC_Format ) {
  40738. extension = extensions.get( 'EXT_texture_compression_bptc' );
  40739. if ( extension !== null ) {
  40740. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  40741. } else {
  40742. return null;
  40743. }
  40744. }
  40745. // RGTC
  40746. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  40747. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  40748. if ( extension !== null ) {
  40749. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  40750. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  40751. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  40752. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  40753. } else {
  40754. return null;
  40755. }
  40756. }
  40757. //
  40758. if ( p === UnsignedInt248Type ) {
  40759. return gl.UNSIGNED_INT_24_8;
  40760. }
  40761. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  40762. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  40763. }
  40764. /**
  40765. * This method can be used to synchronize the CPU with the GPU by waiting until
  40766. * ongoing GPU commands have been completed.
  40767. *
  40768. * @private
  40769. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  40770. */
  40771. _clientWaitAsync() {
  40772. const { gl } = this;
  40773. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  40774. gl.flush();
  40775. return new Promise( ( resolve, reject ) => {
  40776. function test() {
  40777. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  40778. if ( res === gl.WAIT_FAILED ) {
  40779. gl.deleteSync( sync );
  40780. reject();
  40781. return;
  40782. }
  40783. if ( res === gl.TIMEOUT_EXPIRED ) {
  40784. requestAnimationFrame( test );
  40785. return;
  40786. }
  40787. gl.deleteSync( sync );
  40788. resolve();
  40789. }
  40790. test();
  40791. } );
  40792. }
  40793. }
  40794. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  40795. /**
  40796. * A WebGL 2 backend utility module for managing textures.
  40797. *
  40798. * @private
  40799. */
  40800. class WebGLTextureUtils {
  40801. /**
  40802. * Constructs a new utility object.
  40803. *
  40804. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40805. */
  40806. constructor( backend ) {
  40807. /**
  40808. * A reference to the WebGL 2 backend.
  40809. *
  40810. * @type {WebGLBackend}
  40811. */
  40812. this.backend = backend;
  40813. /**
  40814. * A reference to the rendering context.
  40815. *
  40816. * @type {WebGL2RenderingContext}
  40817. */
  40818. this.gl = backend.gl;
  40819. /**
  40820. * A reference to a backend module holding extension-related
  40821. * utility functions.
  40822. *
  40823. * @type {WebGLExtensions}
  40824. */
  40825. this.extensions = backend.extensions;
  40826. /**
  40827. * A dictionary for managing default textures. The key
  40828. * is the binding point (target), the value the WEbGL texture object.
  40829. *
  40830. * @type {Object<GLenum,WebGLTexture>}
  40831. */
  40832. this.defaultTextures = {};
  40833. if ( initialized === false ) {
  40834. this._init();
  40835. initialized = true;
  40836. }
  40837. }
  40838. /**
  40839. * Inits the state of the utility.
  40840. *
  40841. * @private
  40842. */
  40843. _init() {
  40844. const gl = this.gl;
  40845. // Store only WebGL constants here.
  40846. wrappingToGL = {
  40847. [ RepeatWrapping ]: gl.REPEAT,
  40848. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  40849. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  40850. };
  40851. filterToGL = {
  40852. [ NearestFilter ]: gl.NEAREST,
  40853. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  40854. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  40855. [ LinearFilter ]: gl.LINEAR,
  40856. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  40857. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  40858. };
  40859. compareToGL = {
  40860. [ NeverCompare ]: gl.NEVER,
  40861. [ AlwaysCompare ]: gl.ALWAYS,
  40862. [ LessCompare ]: gl.LESS,
  40863. [ LessEqualCompare ]: gl.LEQUAL,
  40864. [ EqualCompare ]: gl.EQUAL,
  40865. [ GreaterEqualCompare ]: gl.GEQUAL,
  40866. [ GreaterCompare ]: gl.GREATER,
  40867. [ NotEqualCompare ]: gl.NOTEQUAL
  40868. };
  40869. }
  40870. /**
  40871. * Returns the native texture type for the given texture.
  40872. *
  40873. * @param {Texture} texture - The texture.
  40874. * @return {GLenum} The native texture type.
  40875. */
  40876. getGLTextureType( texture ) {
  40877. const { gl } = this;
  40878. let glTextureType;
  40879. if ( texture.isCubeTexture === true ) {
  40880. glTextureType = gl.TEXTURE_CUBE_MAP;
  40881. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40882. glTextureType = gl.TEXTURE_2D_ARRAY;
  40883. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  40884. glTextureType = gl.TEXTURE_3D;
  40885. } else {
  40886. glTextureType = gl.TEXTURE_2D;
  40887. }
  40888. return glTextureType;
  40889. }
  40890. /**
  40891. * Returns the native texture type for the given texture.
  40892. *
  40893. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  40894. * @param {GLenum} glFormat - The WebGL format.
  40895. * @param {GLenum} glType - The WebGL type.
  40896. * @param {string} colorSpace - The texture's color space.
  40897. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  40898. * @return {GLenum} The internal format.
  40899. */
  40900. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  40901. const { gl, extensions } = this;
  40902. if ( internalFormatName !== null ) {
  40903. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  40904. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  40905. }
  40906. let internalFormat = glFormat;
  40907. if ( glFormat === gl.RED ) {
  40908. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  40909. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  40910. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  40911. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  40912. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40913. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40914. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40915. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40916. }
  40917. if ( glFormat === gl.RED_INTEGER ) {
  40918. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  40919. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  40920. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  40921. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  40922. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  40923. if ( glType === gl.INT ) internalFormat = gl.R32I;
  40924. }
  40925. if ( glFormat === gl.RG ) {
  40926. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  40927. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  40928. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  40929. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  40930. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40931. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40932. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40933. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40934. }
  40935. if ( glFormat === gl.RG_INTEGER ) {
  40936. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  40937. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  40938. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  40939. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  40940. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  40941. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  40942. }
  40943. if ( glFormat === gl.RGB ) {
  40944. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  40945. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  40946. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  40947. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  40948. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40949. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40950. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40951. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40952. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  40953. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40954. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40955. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40956. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40957. }
  40958. if ( glFormat === gl.RGB_INTEGER ) {
  40959. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40960. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40961. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40962. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40963. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40964. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40965. }
  40966. if ( glFormat === gl.RGBA ) {
  40967. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40968. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40969. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40970. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40971. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40972. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40973. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40974. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40975. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40976. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40977. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40978. }
  40979. if ( glFormat === gl.RGBA_INTEGER ) {
  40980. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40981. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40982. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40983. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40984. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40985. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40986. }
  40987. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40988. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  40989. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  40990. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40991. }
  40992. if ( glFormat === gl.DEPTH_STENCIL ) {
  40993. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40994. }
  40995. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40996. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40997. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40998. extensions.get( 'EXT_color_buffer_float' );
  40999. }
  41000. return internalFormat;
  41001. }
  41002. /**
  41003. * Sets the texture parameters for the given texture.
  41004. *
  41005. * @param {GLenum} textureType - The texture type.
  41006. * @param {Texture} texture - The texture.
  41007. */
  41008. setTextureParameters( textureType, texture ) {
  41009. const { gl, extensions, backend } = this;
  41010. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  41011. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  41012. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  41013. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  41014. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  41015. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  41016. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  41017. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  41018. }
  41019. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  41020. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  41021. // follow WebGPU backend mapping for texture filtering
  41022. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  41023. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  41024. if ( texture.compareFunction ) {
  41025. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  41026. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  41027. }
  41028. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41029. if ( texture.magFilter === NearestFilter ) return;
  41030. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  41031. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  41032. if ( texture.anisotropy > 1 ) {
  41033. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41034. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  41035. }
  41036. }
  41037. }
  41038. /**
  41039. * Creates a default texture for the given texture that can be used
  41040. * as a placeholder until the actual texture is ready for usage.
  41041. *
  41042. * @param {Texture} texture - The texture to create a default texture for.
  41043. */
  41044. createDefaultTexture( texture ) {
  41045. const { gl, backend, defaultTextures } = this;
  41046. const glTextureType = this.getGLTextureType( texture );
  41047. let textureGPU = defaultTextures[ glTextureType ];
  41048. if ( textureGPU === undefined ) {
  41049. textureGPU = gl.createTexture();
  41050. backend.state.bindTexture( glTextureType, textureGPU );
  41051. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  41052. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  41053. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  41054. defaultTextures[ glTextureType ] = textureGPU;
  41055. }
  41056. backend.set( texture, {
  41057. textureGPU,
  41058. glTextureType,
  41059. isDefault: true
  41060. } );
  41061. }
  41062. /**
  41063. * Defines a texture on the GPU for the given texture object.
  41064. *
  41065. * @param {Texture} texture - The texture.
  41066. * @param {Object} [options={}] - Optional configuration parameter.
  41067. * @return {undefined}
  41068. */
  41069. createTexture( texture, options ) {
  41070. const { gl, backend } = this;
  41071. const { levels, width, height, depth } = options;
  41072. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  41073. const glType = backend.utils.convert( texture.type );
  41074. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  41075. const textureGPU = gl.createTexture();
  41076. const glTextureType = this.getGLTextureType( texture );
  41077. backend.state.bindTexture( glTextureType, textureGPU );
  41078. this.setTextureParameters( glTextureType, texture );
  41079. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  41080. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  41081. } else if ( texture.isData3DTexture ) {
  41082. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  41083. } else if ( ! texture.isVideoTexture ) {
  41084. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  41085. }
  41086. backend.set( texture, {
  41087. textureGPU,
  41088. glTextureType,
  41089. glFormat,
  41090. glType,
  41091. glInternalFormat
  41092. } );
  41093. }
  41094. /**
  41095. * Uploads texture buffer data to the GPU memory.
  41096. *
  41097. * @param {WebGLBuffer} buffer - The buffer data.
  41098. * @param {Texture} texture - The texture,
  41099. */
  41100. copyBufferToTexture( buffer, texture ) {
  41101. const { gl, backend } = this;
  41102. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  41103. const { width, height } = texture.source.data;
  41104. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  41105. backend.state.bindTexture( glTextureType, textureGPU );
  41106. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  41107. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  41108. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  41109. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  41110. backend.state.unbindTexture();
  41111. // debug
  41112. // const framebuffer = gl.createFramebuffer();
  41113. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  41114. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  41115. // const readout = new Float32Array( width * height * 4 );
  41116. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  41117. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  41118. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  41119. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  41120. // console.log( readout );
  41121. }
  41122. /**
  41123. * Uploads the updated texture data to the GPU.
  41124. *
  41125. * @param {Texture} texture - The texture.
  41126. * @param {Object} [options={}] - Optional configuration parameter.
  41127. */
  41128. updateTexture( texture, options ) {
  41129. const { gl } = this;
  41130. const { width, height } = options;
  41131. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  41132. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  41133. return;
  41134. const getImage = ( source ) => {
  41135. if ( source.isDataTexture ) {
  41136. return source.image.data;
  41137. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  41138. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  41139. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  41140. source instanceof OffscreenCanvas ) {
  41141. return source;
  41142. }
  41143. return source.data;
  41144. };
  41145. this.backend.state.bindTexture( glTextureType, textureGPU );
  41146. this.setTextureParameters( glTextureType, texture );
  41147. if ( texture.isCompressedTexture ) {
  41148. const mipmaps = texture.mipmaps;
  41149. const image = options.image;
  41150. for ( let i = 0; i < mipmaps.length; i ++ ) {
  41151. const mipmap = mipmaps[ i ];
  41152. if ( texture.isCompressedArrayTexture ) {
  41153. if ( texture.format !== gl.RGBA ) {
  41154. if ( glFormat !== null ) {
  41155. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  41156. } else {
  41157. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  41158. }
  41159. } else {
  41160. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  41161. }
  41162. } else {
  41163. if ( glFormat !== null ) {
  41164. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  41165. } else {
  41166. console.warn( 'Unsupported compressed texture format' );
  41167. }
  41168. }
  41169. }
  41170. } else if ( texture.isCubeTexture ) {
  41171. const images = options.images;
  41172. for ( let i = 0; i < 6; i ++ ) {
  41173. const image = getImage( images[ i ] );
  41174. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  41175. }
  41176. } else if ( texture.isDataArrayTexture ) {
  41177. const image = options.image;
  41178. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  41179. } else if ( texture.isData3DTexture ) {
  41180. const image = options.image;
  41181. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  41182. } else if ( texture.isVideoTexture ) {
  41183. texture.update();
  41184. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  41185. } else {
  41186. const image = getImage( options.image );
  41187. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  41188. }
  41189. }
  41190. /**
  41191. * Generates mipmaps for the given texture.
  41192. *
  41193. * @param {Texture} texture - The texture.
  41194. */
  41195. generateMipmaps( texture ) {
  41196. const { gl, backend } = this;
  41197. const { textureGPU, glTextureType } = backend.get( texture );
  41198. backend.state.bindTexture( glTextureType, textureGPU );
  41199. gl.generateMipmap( glTextureType );
  41200. }
  41201. /**
  41202. * Deallocates the render buffers of the given render target.
  41203. *
  41204. * @param {RenderTarget} renderTarget - The render target.
  41205. */
  41206. deallocateRenderBuffers( renderTarget ) {
  41207. const { gl, backend } = this;
  41208. // remove framebuffer reference
  41209. if ( renderTarget ) {
  41210. const renderContextData = backend.get( renderTarget );
  41211. renderContextData.renderBufferStorageSetup = undefined;
  41212. if ( renderContextData.framebuffers ) {
  41213. for ( const cacheKey in renderContextData.framebuffers ) {
  41214. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  41215. }
  41216. delete renderContextData.framebuffers;
  41217. }
  41218. if ( renderContextData.depthRenderbuffer ) {
  41219. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  41220. delete renderContextData.depthRenderbuffer;
  41221. }
  41222. if ( renderContextData.stencilRenderbuffer ) {
  41223. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  41224. delete renderContextData.stencilRenderbuffer;
  41225. }
  41226. if ( renderContextData.msaaFrameBuffer ) {
  41227. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  41228. delete renderContextData.msaaFrameBuffer;
  41229. }
  41230. if ( renderContextData.msaaRenderbuffers ) {
  41231. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  41232. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  41233. }
  41234. delete renderContextData.msaaRenderbuffers;
  41235. }
  41236. }
  41237. }
  41238. /**
  41239. * Destroys the GPU data for the given texture object.
  41240. *
  41241. * @param {Texture} texture - The texture.
  41242. */
  41243. destroyTexture( texture ) {
  41244. const { gl, backend } = this;
  41245. const { textureGPU, renderTarget } = backend.get( texture );
  41246. this.deallocateRenderBuffers( renderTarget );
  41247. gl.deleteTexture( textureGPU );
  41248. backend.delete( texture );
  41249. }
  41250. /**
  41251. * Copies data of the given source texture to the given destination texture.
  41252. *
  41253. * @param {Texture} srcTexture - The source texture.
  41254. * @param {Texture} dstTexture - The destination texture.
  41255. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  41256. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  41257. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41258. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41259. */
  41260. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  41261. const { gl, backend } = this;
  41262. const { state } = this.backend;
  41263. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  41264. state.bindTexture( glTextureType, dstTextureGPU );
  41265. // gather the necessary dimensions to copy
  41266. let width, height, depth, minX, minY, minZ;
  41267. let dstX, dstY, dstZ;
  41268. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  41269. if ( srcRegion !== null ) {
  41270. width = srcRegion.max.x - srcRegion.min.x;
  41271. height = srcRegion.max.y - srcRegion.min.y;
  41272. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  41273. minX = srcRegion.min.x;
  41274. minY = srcRegion.min.y;
  41275. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  41276. } else {
  41277. const levelScale = Math.pow( 2, - srcLevel );
  41278. width = Math.floor( image.width * levelScale );
  41279. height = Math.floor( image.height * levelScale );
  41280. if ( srcTexture.isDataArrayTexture ) {
  41281. depth = image.depth;
  41282. } else if ( srcTexture.isData3DTexture ) {
  41283. depth = Math.floor( image.depth * levelScale );
  41284. } else {
  41285. depth = 1;
  41286. }
  41287. minX = 0;
  41288. minY = 0;
  41289. minZ = 0;
  41290. }
  41291. if ( dstPosition !== null ) {
  41292. dstX = dstPosition.x;
  41293. dstY = dstPosition.y;
  41294. dstZ = dstPosition.z;
  41295. } else {
  41296. dstX = 0;
  41297. dstY = 0;
  41298. dstZ = 0;
  41299. }
  41300. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  41301. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  41302. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  41303. // used for copying data from cpu
  41304. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  41305. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  41306. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  41307. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  41308. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  41309. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  41310. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  41311. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  41312. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  41313. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  41314. // set up the src texture
  41315. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  41316. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  41317. const srcTextureData = backend.get( srcTexture );
  41318. const dstTextureData = backend.get( dstTexture );
  41319. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  41320. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  41321. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  41322. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  41323. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  41324. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  41325. let mask = gl.COLOR_BUFFER_BIT;
  41326. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  41327. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  41328. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  41329. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  41330. } else {
  41331. if ( isDst3D ) {
  41332. // copy data into the 3d texture
  41333. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  41334. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  41335. } else if ( dstTexture.isCompressedArrayTexture ) {
  41336. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  41337. } else {
  41338. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  41339. }
  41340. } else {
  41341. // copy data into the 2d texture
  41342. if ( srcTexture.isDataTexture ) {
  41343. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  41344. } else if ( srcTexture.isCompressedTexture ) {
  41345. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  41346. } else {
  41347. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  41348. }
  41349. }
  41350. }
  41351. // reset values
  41352. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  41353. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  41354. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  41355. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  41356. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  41357. // Generate mipmaps only when copying level 0
  41358. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  41359. gl.generateMipmap( glTextureType );
  41360. }
  41361. state.unbindTexture();
  41362. }
  41363. /**
  41364. * Copies the current bound framebuffer to the given texture.
  41365. *
  41366. * @param {Texture} texture - The destination texture.
  41367. * @param {RenderContext} renderContext - The render context.
  41368. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41369. */
  41370. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41371. const { gl } = this;
  41372. const { state } = this.backend;
  41373. const { textureGPU } = this.backend.get( texture );
  41374. const { x, y, z: width, w: height } = rectangle;
  41375. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  41376. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  41377. if ( requireDrawFrameBuffer ) {
  41378. const partial = ( x !== 0 || y !== 0 );
  41379. let mask;
  41380. let attachment;
  41381. if ( texture.isDepthTexture === true ) {
  41382. mask = gl.DEPTH_BUFFER_BIT;
  41383. attachment = gl.DEPTH_ATTACHMENT;
  41384. if ( renderContext.stencil ) {
  41385. mask |= gl.STENCIL_BUFFER_BIT;
  41386. }
  41387. } else {
  41388. mask = gl.COLOR_BUFFER_BIT;
  41389. attachment = gl.COLOR_ATTACHMENT0;
  41390. }
  41391. if ( partial ) {
  41392. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  41393. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  41394. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41395. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41396. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  41397. const flippedY = srcHeight - y - height;
  41398. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  41399. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  41400. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  41401. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  41402. state.unbindTexture();
  41403. } else {
  41404. const fb = gl.createFramebuffer();
  41405. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  41406. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  41407. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  41408. gl.deleteFramebuffer( fb );
  41409. }
  41410. } else {
  41411. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  41412. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  41413. state.unbindTexture();
  41414. }
  41415. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  41416. this.backend._setFramebuffer( renderContext );
  41417. }
  41418. /**
  41419. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  41420. *
  41421. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  41422. * @param {RenderContext} renderContext - The render context.
  41423. * @param {number} samples - The MSAA sample count.
  41424. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  41425. */
  41426. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  41427. const { gl } = this;
  41428. const renderTarget = renderContext.renderTarget;
  41429. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  41430. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  41431. if ( depthBuffer && ! stencilBuffer ) {
  41432. let glInternalFormat = gl.DEPTH_COMPONENT24;
  41433. if ( useMultisampledRTT === true ) {
  41434. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  41435. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  41436. } else if ( samples > 0 ) {
  41437. if ( depthTexture && depthTexture.isDepthTexture ) {
  41438. if ( depthTexture.type === gl.FLOAT ) {
  41439. glInternalFormat = gl.DEPTH_COMPONENT32F;
  41440. }
  41441. }
  41442. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  41443. } else {
  41444. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  41445. }
  41446. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  41447. } else if ( depthBuffer && stencilBuffer ) {
  41448. if ( samples > 0 ) {
  41449. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  41450. } else {
  41451. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  41452. }
  41453. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  41454. }
  41455. }
  41456. /**
  41457. * Returns texture data as a typed array.
  41458. *
  41459. * @async
  41460. * @param {Texture} texture - The texture to copy.
  41461. * @param {number} x - The x coordinate of the copy origin.
  41462. * @param {number} y - The y coordinate of the copy origin.
  41463. * @param {number} width - The width of the copy.
  41464. * @param {number} height - The height of the copy.
  41465. * @param {number} faceIndex - The face index.
  41466. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41467. */
  41468. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41469. const { backend, gl } = this;
  41470. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  41471. const fb = gl.createFramebuffer();
  41472. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  41473. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  41474. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  41475. const typedArrayType = this._getTypedArrayType( glType );
  41476. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  41477. const elementCount = width * height;
  41478. const byteLength = elementCount * bytesPerTexel;
  41479. const buffer = gl.createBuffer();
  41480. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  41481. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  41482. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  41483. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  41484. await backend.utils._clientWaitAsync();
  41485. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  41486. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  41487. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  41488. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  41489. gl.deleteFramebuffer( fb );
  41490. return dstBuffer;
  41491. }
  41492. /**
  41493. * Returns the corresponding typed array type for the given WebGL data type.
  41494. *
  41495. * @private
  41496. * @param {GLenum} glType - The WebGL data type.
  41497. * @return {TypedArray.constructor} The typed array type.
  41498. */
  41499. _getTypedArrayType( glType ) {
  41500. const { gl } = this;
  41501. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  41502. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  41503. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  41504. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  41505. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  41506. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  41507. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  41508. if ( glType === gl.FLOAT ) return Float32Array;
  41509. throw new Error( `Unsupported WebGL type: ${glType}` );
  41510. }
  41511. /**
  41512. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  41513. *
  41514. * @private
  41515. * @param {GLenum} glType - The WebGL data type.
  41516. * @param {GLenum} glFormat - The WebGL texture format.
  41517. * @return {number} The bytes-per-texel.
  41518. */
  41519. _getBytesPerTexel( glType, glFormat ) {
  41520. const { gl } = this;
  41521. let bytesPerComponent = 0;
  41522. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  41523. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  41524. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  41525. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  41526. glType === gl.UNSIGNED_SHORT ||
  41527. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  41528. if ( glType === gl.UNSIGNED_INT ||
  41529. glType === gl.FLOAT ) bytesPerComponent = 4;
  41530. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  41531. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  41532. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  41533. }
  41534. }
  41535. /**
  41536. * A WebGL 2 backend utility module for managing extensions.
  41537. *
  41538. * @private
  41539. */
  41540. class WebGLExtensions {
  41541. /**
  41542. * Constructs a new utility object.
  41543. *
  41544. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41545. */
  41546. constructor( backend ) {
  41547. /**
  41548. * A reference to the WebGL 2 backend.
  41549. *
  41550. * @type {WebGLBackend}
  41551. */
  41552. this.backend = backend;
  41553. /**
  41554. * A reference to the rendering context.
  41555. *
  41556. * @type {WebGL2RenderingContext}
  41557. */
  41558. this.gl = this.backend.gl;
  41559. /**
  41560. * A list with all the supported WebGL extensions.
  41561. *
  41562. * @type {Array<string>}
  41563. */
  41564. this.availableExtensions = this.gl.getSupportedExtensions();
  41565. /**
  41566. * A dictionary with requested WebGL extensions.
  41567. * The key is the name of the extension, the value
  41568. * the requested extension object.
  41569. *
  41570. * @type {Object<string,Object>}
  41571. */
  41572. this.extensions = {};
  41573. }
  41574. /**
  41575. * Returns the extension object for the given extension name.
  41576. *
  41577. * @param {string} name - The extension name.
  41578. * @return {Object} The extension object.
  41579. */
  41580. get( name ) {
  41581. let extension = this.extensions[ name ];
  41582. if ( extension === undefined ) {
  41583. extension = this.gl.getExtension( name );
  41584. this.extensions[ name ] = extension;
  41585. }
  41586. return extension;
  41587. }
  41588. /**
  41589. * Returns `true` if the requested extension is available.
  41590. *
  41591. * @param {string} name - The extension name.
  41592. * @return {boolean} Whether the given extension is available or not.
  41593. */
  41594. has( name ) {
  41595. return this.availableExtensions.includes( name );
  41596. }
  41597. }
  41598. /**
  41599. * A WebGL 2 backend utility module for managing the device's capabilities.
  41600. *
  41601. * @private
  41602. */
  41603. class WebGLCapabilities {
  41604. /**
  41605. * Constructs a new utility object.
  41606. *
  41607. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41608. */
  41609. constructor( backend ) {
  41610. /**
  41611. * A reference to the WebGL 2 backend.
  41612. *
  41613. * @type {WebGLBackend}
  41614. */
  41615. this.backend = backend;
  41616. /**
  41617. * This value holds the cached max anisotropy value.
  41618. *
  41619. * @type {?number}
  41620. * @default null
  41621. */
  41622. this.maxAnisotropy = null;
  41623. }
  41624. /**
  41625. * Returns the maximum anisotropy texture filtering value. This value
  41626. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  41627. * WebGL extension.
  41628. *
  41629. * @return {number} The maximum anisotropy texture filtering value.
  41630. */
  41631. getMaxAnisotropy() {
  41632. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  41633. const gl = this.backend.gl;
  41634. const extensions = this.backend.extensions;
  41635. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41636. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41637. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  41638. } else {
  41639. this.maxAnisotropy = 0;
  41640. }
  41641. return this.maxAnisotropy;
  41642. }
  41643. }
  41644. const GLFeatureName = {
  41645. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  41646. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  41647. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  41648. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  41649. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41650. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  41651. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  41652. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  41653. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  41654. };
  41655. class WebGLBufferRenderer {
  41656. constructor( backend ) {
  41657. this.gl = backend.gl;
  41658. this.extensions = backend.extensions;
  41659. this.info = backend.renderer.info;
  41660. this.mode = null;
  41661. this.index = 0;
  41662. this.type = null;
  41663. this.object = null;
  41664. }
  41665. render( start, count ) {
  41666. const { gl, mode, object, type, info, index } = this;
  41667. if ( index !== 0 ) {
  41668. gl.drawElements( mode, count, type, start );
  41669. } else {
  41670. gl.drawArrays( mode, start, count );
  41671. }
  41672. info.update( object, count, 1 );
  41673. }
  41674. renderInstances( start, count, primcount ) {
  41675. const { gl, mode, type, index, object, info } = this;
  41676. if ( primcount === 0 ) return;
  41677. if ( index !== 0 ) {
  41678. gl.drawElementsInstanced( mode, count, type, start, primcount );
  41679. } else {
  41680. gl.drawArraysInstanced( mode, start, count, primcount );
  41681. }
  41682. info.update( object, count, primcount );
  41683. }
  41684. renderMultiDraw( starts, counts, drawCount ) {
  41685. const { extensions, mode, object, info } = this;
  41686. if ( drawCount === 0 ) return;
  41687. const extension = extensions.get( 'WEBGL_multi_draw' );
  41688. if ( extension === null ) {
  41689. for ( let i = 0; i < drawCount; i ++ ) {
  41690. this.render( starts[ i ], counts[ i ] );
  41691. }
  41692. } else {
  41693. if ( this.index !== 0 ) {
  41694. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  41695. } else {
  41696. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  41697. }
  41698. let elementCount = 0;
  41699. for ( let i = 0; i < drawCount; i ++ ) {
  41700. elementCount += counts[ i ];
  41701. }
  41702. info.update( object, elementCount, 1 );
  41703. }
  41704. }
  41705. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  41706. const { extensions, mode, object, info } = this;
  41707. if ( drawCount === 0 ) return;
  41708. const extension = extensions.get( 'WEBGL_multi_draw' );
  41709. if ( extension === null ) {
  41710. for ( let i = 0; i < drawCount; i ++ ) {
  41711. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  41712. }
  41713. } else {
  41714. if ( this.index !== 0 ) {
  41715. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  41716. } else {
  41717. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  41718. }
  41719. let elementCount = 0;
  41720. for ( let i = 0; i < drawCount; i ++ ) {
  41721. elementCount += counts[ i ] * primcount[ i ];
  41722. }
  41723. info.update( object, elementCount, 1 );
  41724. }
  41725. }
  41726. //
  41727. }
  41728. /**
  41729. * Abstract base class of a timestamp query pool.
  41730. *
  41731. * @abstract
  41732. */
  41733. class TimestampQueryPool {
  41734. /**
  41735. * Creates a new timestamp query pool.
  41736. *
  41737. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  41738. */
  41739. constructor( maxQueries = 256 ) {
  41740. /**
  41741. * Whether to track timestamps or not.
  41742. *
  41743. * @type {boolean}
  41744. * @default true
  41745. */
  41746. this.trackTimestamp = true;
  41747. /**
  41748. * Maximum number of queries this pool can hold.
  41749. *
  41750. * @type {number}
  41751. * @default 256
  41752. */
  41753. this.maxQueries = maxQueries;
  41754. /**
  41755. * How many queries allocated so far.
  41756. *
  41757. * @type {number}
  41758. * @default 0
  41759. */
  41760. this.currentQueryIndex = 0;
  41761. /**
  41762. * Tracks offsets for different contexts.
  41763. *
  41764. * @type {Map<string, number>}
  41765. */
  41766. this.queryOffsets = new Map();
  41767. /**
  41768. * Whether the pool has been disposed or not.
  41769. *
  41770. * @type {boolean}
  41771. * @default false
  41772. */
  41773. this.isDisposed = false;
  41774. /**
  41775. * TODO
  41776. *
  41777. * @type {number}
  41778. * @default 0
  41779. */
  41780. this.lastValue = 0;
  41781. /**
  41782. * TODO
  41783. *
  41784. * @type {boolean}
  41785. * @default false
  41786. */
  41787. this.pendingResolve = false;
  41788. }
  41789. /**
  41790. * Allocate queries for a specific renderContext.
  41791. *
  41792. * @abstract
  41793. * @param {Object} renderContext - The render context to allocate queries for.
  41794. */
  41795. allocateQueriesForContext( /* renderContext */ ) {}
  41796. /**
  41797. * Resolve all timestamps and return data (or process them).
  41798. *
  41799. * @abstract
  41800. * @async
  41801. * @returns {Promise<number>|number} The resolved timestamp value.
  41802. */
  41803. async resolveQueriesAsync() {}
  41804. /**
  41805. * Dispose of the query pool.
  41806. *
  41807. * @abstract
  41808. */
  41809. dispose() {}
  41810. }
  41811. /**
  41812. * Manages a pool of WebGL timestamp queries for performance measurement.
  41813. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  41814. *
  41815. * @augments TimestampQueryPool
  41816. */
  41817. class WebGLTimestampQueryPool extends TimestampQueryPool {
  41818. /**
  41819. * Creates a new WebGL timestamp query pool.
  41820. *
  41821. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  41822. * @param {string} type - The type identifier for this query pool.
  41823. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  41824. */
  41825. constructor( gl, type, maxQueries = 2048 ) {
  41826. super( maxQueries );
  41827. this.gl = gl;
  41828. this.type = type;
  41829. // Check for timer query extensions
  41830. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  41831. gl.getExtension( 'EXT_disjoint_timer_query' );
  41832. if ( ! this.ext ) {
  41833. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  41834. this.trackTimestamp = false;
  41835. return;
  41836. }
  41837. // Create query objects
  41838. this.queries = [];
  41839. for ( let i = 0; i < this.maxQueries; i ++ ) {
  41840. this.queries.push( gl.createQuery() );
  41841. }
  41842. this.activeQuery = null;
  41843. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  41844. }
  41845. /**
  41846. * Allocates a pair of queries for a given render context.
  41847. *
  41848. * @param {Object} renderContext - The render context to allocate queries for.
  41849. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  41850. */
  41851. allocateQueriesForContext( renderContext ) {
  41852. if ( ! this.trackTimestamp ) return null;
  41853. // Check if we have enough space for a new query pair
  41854. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  41855. 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() } ).` );
  41856. return null;
  41857. }
  41858. const baseOffset = this.currentQueryIndex;
  41859. this.currentQueryIndex += 2;
  41860. // Initialize query states
  41861. this.queryStates.set( baseOffset, 'inactive' );
  41862. this.queryOffsets.set( renderContext.id, baseOffset );
  41863. return baseOffset;
  41864. }
  41865. /**
  41866. * Begins a timestamp query for the specified render context.
  41867. *
  41868. * @param {Object} renderContext - The render context to begin timing for.
  41869. */
  41870. beginQuery( renderContext ) {
  41871. if ( ! this.trackTimestamp || this.isDisposed ) {
  41872. return;
  41873. }
  41874. const baseOffset = this.queryOffsets.get( renderContext.id );
  41875. if ( baseOffset == null ) {
  41876. return;
  41877. }
  41878. // Don't start a new query if there's an active one
  41879. if ( this.activeQuery !== null ) {
  41880. return;
  41881. }
  41882. const query = this.queries[ baseOffset ];
  41883. if ( ! query ) {
  41884. return;
  41885. }
  41886. try {
  41887. // Only begin if query is inactive
  41888. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  41889. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  41890. this.activeQuery = baseOffset;
  41891. this.queryStates.set( baseOffset, 'started' );
  41892. }
  41893. } catch ( error ) {
  41894. console.error( 'Error in beginQuery:', error );
  41895. this.activeQuery = null;
  41896. this.queryStates.set( baseOffset, 'inactive' );
  41897. }
  41898. }
  41899. /**
  41900. * Ends the active timestamp query for the specified render context.
  41901. *
  41902. * @param {Object} renderContext - The render context to end timing for.
  41903. * @param {string} renderContext.id - Unique identifier for the render context.
  41904. */
  41905. endQuery( renderContext ) {
  41906. if ( ! this.trackTimestamp || this.isDisposed ) {
  41907. return;
  41908. }
  41909. const baseOffset = this.queryOffsets.get( renderContext.id );
  41910. if ( baseOffset == null ) {
  41911. return;
  41912. }
  41913. // Only end if this is the active query
  41914. if ( this.activeQuery !== baseOffset ) {
  41915. return;
  41916. }
  41917. try {
  41918. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  41919. this.queryStates.set( baseOffset, 'ended' );
  41920. this.activeQuery = null;
  41921. } catch ( error ) {
  41922. console.error( 'Error in endQuery:', error );
  41923. // Reset state on error
  41924. this.queryStates.set( baseOffset, 'inactive' );
  41925. this.activeQuery = null;
  41926. }
  41927. }
  41928. /**
  41929. * Asynchronously resolves all completed queries and returns the total duration.
  41930. *
  41931. * @async
  41932. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  41933. */
  41934. async resolveQueriesAsync() {
  41935. if ( ! this.trackTimestamp || this.pendingResolve ) {
  41936. return this.lastValue;
  41937. }
  41938. this.pendingResolve = true;
  41939. try {
  41940. // Wait for all ended queries to complete
  41941. const resolvePromises = [];
  41942. for ( const [ baseOffset, state ] of this.queryStates ) {
  41943. if ( state === 'ended' ) {
  41944. const query = this.queries[ baseOffset ];
  41945. resolvePromises.push( this.resolveQuery( query ) );
  41946. }
  41947. }
  41948. if ( resolvePromises.length === 0 ) {
  41949. return this.lastValue;
  41950. }
  41951. const results = await Promise.all( resolvePromises );
  41952. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  41953. // Store the last valid result
  41954. this.lastValue = totalDuration;
  41955. // Reset states
  41956. this.currentQueryIndex = 0;
  41957. this.queryOffsets.clear();
  41958. this.queryStates.clear();
  41959. this.activeQuery = null;
  41960. return totalDuration;
  41961. } catch ( error ) {
  41962. console.error( 'Error resolving queries:', error );
  41963. return this.lastValue;
  41964. } finally {
  41965. this.pendingResolve = false;
  41966. }
  41967. }
  41968. /**
  41969. * Resolves a single query, checking for completion and disjoint operation.
  41970. *
  41971. * @async
  41972. * @param {WebGLQuery} query - The query object to resolve.
  41973. * @returns {Promise<number>} The elapsed time in milliseconds.
  41974. */
  41975. async resolveQuery( query ) {
  41976. return new Promise( ( resolve ) => {
  41977. if ( this.isDisposed ) {
  41978. resolve( this.lastValue );
  41979. return;
  41980. }
  41981. let timeoutId;
  41982. let isResolved = false;
  41983. const cleanup = () => {
  41984. if ( timeoutId ) {
  41985. clearTimeout( timeoutId );
  41986. timeoutId = null;
  41987. }
  41988. };
  41989. const finalizeResolution = ( value ) => {
  41990. if ( ! isResolved ) {
  41991. isResolved = true;
  41992. cleanup();
  41993. resolve( value );
  41994. }
  41995. };
  41996. const checkQuery = () => {
  41997. if ( this.isDisposed ) {
  41998. finalizeResolution( this.lastValue );
  41999. return;
  42000. }
  42001. try {
  42002. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  42003. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  42004. if ( disjoint ) {
  42005. finalizeResolution( this.lastValue );
  42006. return;
  42007. }
  42008. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  42009. if ( ! available ) {
  42010. timeoutId = setTimeout( checkQuery, 1 );
  42011. return;
  42012. }
  42013. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  42014. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  42015. } catch ( error ) {
  42016. console.error( 'Error checking query:', error );
  42017. resolve( this.lastValue );
  42018. }
  42019. };
  42020. checkQuery();
  42021. } );
  42022. }
  42023. /**
  42024. * Releases all resources held by this query pool.
  42025. * This includes deleting all query objects and clearing internal state.
  42026. */
  42027. dispose() {
  42028. if ( this.isDisposed ) {
  42029. return;
  42030. }
  42031. this.isDisposed = true;
  42032. if ( ! this.trackTimestamp ) return;
  42033. for ( const query of this.queries ) {
  42034. this.gl.deleteQuery( query );
  42035. }
  42036. this.queries = [];
  42037. this.queryStates.clear();
  42038. this.queryOffsets.clear();
  42039. this.lastValue = 0;
  42040. this.activeQuery = null;
  42041. }
  42042. }
  42043. /**
  42044. * A backend implementation targeting WebGL 2.
  42045. *
  42046. * @private
  42047. * @augments Backend
  42048. */
  42049. class WebGLBackend extends Backend {
  42050. /**
  42051. * WebGLBackend options.
  42052. *
  42053. * @typedef {Object} WebGLBackend~Options
  42054. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  42055. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  42056. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  42057. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  42058. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  42059. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  42060. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  42061. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  42062. */
  42063. /**
  42064. * Constructs a new WebGPU backend.
  42065. *
  42066. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  42067. */
  42068. constructor( parameters = {} ) {
  42069. super( parameters );
  42070. /**
  42071. * This flag can be used for type testing.
  42072. *
  42073. * @type {boolean}
  42074. * @readonly
  42075. * @default true
  42076. */
  42077. this.isWebGLBackend = true;
  42078. /**
  42079. * A reference to a backend module holding shader attribute-related
  42080. * utility functions.
  42081. *
  42082. * @type {?WebGLAttributeUtils}
  42083. * @default null
  42084. */
  42085. this.attributeUtils = null;
  42086. /**
  42087. * A reference to a backend module holding extension-related
  42088. * utility functions.
  42089. *
  42090. * @type {?WebGLExtensions}
  42091. * @default null
  42092. */
  42093. this.extensions = null;
  42094. /**
  42095. * A reference to a backend module holding capability-related
  42096. * utility functions.
  42097. *
  42098. * @type {?WebGLCapabilities}
  42099. * @default null
  42100. */
  42101. this.capabilities = null;
  42102. /**
  42103. * A reference to a backend module holding texture-related
  42104. * utility functions.
  42105. *
  42106. * @type {?WebGLTextureUtils}
  42107. * @default null
  42108. */
  42109. this.textureUtils = null;
  42110. /**
  42111. * A reference to a backend module holding renderer-related
  42112. * utility functions.
  42113. *
  42114. * @type {?WebGLBufferRenderer}
  42115. * @default null
  42116. */
  42117. this.bufferRenderer = null;
  42118. /**
  42119. * A reference to the rendering context.
  42120. *
  42121. * @type {?WebGL2RenderingContext}
  42122. * @default null
  42123. */
  42124. this.gl = null;
  42125. /**
  42126. * A reference to a backend module holding state-related
  42127. * utility functions.
  42128. *
  42129. * @type {?WebGLState}
  42130. * @default null
  42131. */
  42132. this.state = null;
  42133. /**
  42134. * A reference to a backend module holding common
  42135. * utility functions.
  42136. *
  42137. * @type {?WebGLUtils}
  42138. * @default null
  42139. */
  42140. this.utils = null;
  42141. /**
  42142. * Dictionary for caching VAOs.
  42143. *
  42144. * @type {Object<string,WebGLVertexArrayObject>}
  42145. */
  42146. this.vaoCache = {};
  42147. /**
  42148. * Dictionary for caching transform feedback objects.
  42149. *
  42150. * @type {Object<string,WebGLTransformFeedback>}
  42151. */
  42152. this.transformFeedbackCache = {};
  42153. /**
  42154. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  42155. * Only relevant when using compute shaders.
  42156. *
  42157. * @type {boolean}
  42158. * @default false
  42159. */
  42160. this.discard = false;
  42161. /**
  42162. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  42163. * device does not support the extension.
  42164. *
  42165. * @type {?EXTDisjointTimerQueryWebGL2}
  42166. * @default null
  42167. */
  42168. this.disjoint = null;
  42169. /**
  42170. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  42171. * device does not support the extension.
  42172. *
  42173. * @type {?KHRParallelShaderCompile}
  42174. * @default null
  42175. */
  42176. this.parallel = null;
  42177. /**
  42178. * A reference to the current render context.
  42179. *
  42180. * @private
  42181. * @type {RenderContext}
  42182. * @default null
  42183. */
  42184. this._currentContext = null;
  42185. /**
  42186. * A unique collection of bindings.
  42187. *
  42188. * @private
  42189. * @type {WeakSet}
  42190. */
  42191. this._knownBindings = new WeakSet();
  42192. /**
  42193. * Whether the device supports framebuffers invalidation or not.
  42194. *
  42195. * @private
  42196. * @type {boolean}
  42197. */
  42198. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  42199. /**
  42200. * The target framebuffer when rendering with
  42201. * the WebXR device API.
  42202. *
  42203. * @private
  42204. * @type {WebGLFramebuffer}
  42205. * @default null
  42206. */
  42207. this._xrFramebuffer = null;
  42208. }
  42209. /**
  42210. * Initializes the backend so it is ready for usage.
  42211. *
  42212. * @param {Renderer} renderer - The renderer.
  42213. */
  42214. init( renderer ) {
  42215. super.init( renderer );
  42216. //
  42217. const parameters = this.parameters;
  42218. const contextAttributes = {
  42219. antialias: renderer.samples > 0,
  42220. alpha: true, // always true for performance reasons
  42221. depth: renderer.depth,
  42222. stencil: renderer.stencil
  42223. };
  42224. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  42225. function onContextLost( event ) {
  42226. event.preventDefault();
  42227. const contextLossInfo = {
  42228. api: 'WebGL',
  42229. message: event.statusMessage || 'Unknown reason',
  42230. reason: null,
  42231. originalEvent: event
  42232. };
  42233. renderer.onDeviceLost( contextLossInfo );
  42234. }
  42235. this._onContextLost = onContextLost;
  42236. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  42237. this.gl = glContext;
  42238. this.extensions = new WebGLExtensions( this );
  42239. this.capabilities = new WebGLCapabilities( this );
  42240. this.attributeUtils = new WebGLAttributeUtils( this );
  42241. this.textureUtils = new WebGLTextureUtils( this );
  42242. this.bufferRenderer = new WebGLBufferRenderer( this );
  42243. this.state = new WebGLState( this );
  42244. this.utils = new WebGLUtils( this );
  42245. this.extensions.get( 'EXT_color_buffer_float' );
  42246. this.extensions.get( 'WEBGL_clip_cull_distance' );
  42247. this.extensions.get( 'OES_texture_float_linear' );
  42248. this.extensions.get( 'EXT_color_buffer_half_float' );
  42249. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42250. this.extensions.get( 'WEBGL_render_shared_exponent' );
  42251. this.extensions.get( 'WEBGL_multi_draw' );
  42252. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  42253. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  42254. }
  42255. /**
  42256. * The coordinate system of the backend.
  42257. *
  42258. * @type {number}
  42259. * @readonly
  42260. */
  42261. get coordinateSystem() {
  42262. return WebGLCoordinateSystem;
  42263. }
  42264. /**
  42265. * This method performs a readback operation by moving buffer data from
  42266. * a storage buffer attribute from the GPU to the CPU.
  42267. *
  42268. * @async
  42269. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42270. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42271. */
  42272. async getArrayBufferAsync( attribute ) {
  42273. return await this.attributeUtils.getArrayBufferAsync( attribute );
  42274. }
  42275. /**
  42276. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  42277. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  42278. *
  42279. * @async
  42280. * @return {Promise} A Promise that resolves when synchronization has been finished.
  42281. */
  42282. async waitForGPU() {
  42283. await this.utils._clientWaitAsync();
  42284. }
  42285. /**
  42286. * Ensures the backend is XR compatible.
  42287. *
  42288. * @async
  42289. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  42290. */
  42291. async makeXRCompatible() {
  42292. const attributes = this.gl.getContextAttributes();
  42293. if ( attributes.xrCompatible !== true ) {
  42294. await this.gl.makeXRCompatible();
  42295. }
  42296. }
  42297. /**
  42298. * Sets the XR rendering destination.
  42299. *
  42300. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  42301. */
  42302. setXRTarget( xrFramebuffer ) {
  42303. this._xrFramebuffer = xrFramebuffer;
  42304. }
  42305. /**
  42306. * Configures the given XR render target with external textures.
  42307. *
  42308. * This method is only relevant when using the WebXR Layers API.
  42309. *
  42310. * @param {XRRenderTarget} renderTarget - The XR render target.
  42311. * @param {WebGLTexture} colorTexture - A native color texture.
  42312. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  42313. */
  42314. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  42315. const gl = this.gl;
  42316. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  42317. if ( depthTexture !== null ) {
  42318. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  42319. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  42320. // The multisample_render_to_texture extension doesn't work properly if there
  42321. // are midframe flushes and an external depth texture.
  42322. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget.autoAllocateDepthBuffer ) {
  42323. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  42324. }
  42325. renderTarget.autoAllocateDepthBuffer = false;
  42326. }
  42327. }
  42328. /**
  42329. * Inits a time stamp query for the given render context.
  42330. *
  42331. * @param {RenderContext} renderContext - The render context.
  42332. */
  42333. initTimestampQuery( renderContext ) {
  42334. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  42335. const type = renderContext.isComputeNode ? 'compute' : 'render';
  42336. if ( ! this.timestampQueryPool[ type ] ) {
  42337. // TODO: Variable maxQueries?
  42338. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  42339. }
  42340. const timestampQueryPool = this.timestampQueryPool[ type ];
  42341. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  42342. if ( baseOffset !== null ) {
  42343. timestampQueryPool.beginQuery( renderContext );
  42344. }
  42345. }
  42346. // timestamp utils
  42347. /**
  42348. * Prepares the timestamp buffer.
  42349. *
  42350. * @param {RenderContext} renderContext - The render context.
  42351. */
  42352. prepareTimestampBuffer( renderContext ) {
  42353. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  42354. const type = renderContext.isComputeNode ? 'compute' : 'render';
  42355. const timestampQueryPool = this.timestampQueryPool[ type ];
  42356. timestampQueryPool.endQuery( renderContext );
  42357. }
  42358. /**
  42359. * Returns the backend's rendering context.
  42360. *
  42361. * @return {WebGL2RenderingContext} The rendering context.
  42362. */
  42363. getContext() {
  42364. return this.gl;
  42365. }
  42366. /**
  42367. * This method is executed at the beginning of a render call and prepares
  42368. * the WebGL state for upcoming render calls
  42369. *
  42370. * @param {RenderContext} renderContext - The render context.
  42371. */
  42372. beginRender( renderContext ) {
  42373. const { state, gl } = this;
  42374. const renderContextData = this.get( renderContext );
  42375. //
  42376. if ( renderContext.viewport ) {
  42377. this.updateViewport( renderContext );
  42378. } else {
  42379. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  42380. }
  42381. if ( renderContext.scissor ) {
  42382. const { x, y, width, height } = renderContext.scissorValue;
  42383. state.scissor( x, renderContext.height - height - y, width, height );
  42384. }
  42385. //
  42386. this.initTimestampQuery( renderContext );
  42387. renderContextData.previousContext = this._currentContext;
  42388. this._currentContext = renderContext;
  42389. this._setFramebuffer( renderContext );
  42390. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  42391. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42392. if ( occlusionQueryCount > 0 ) {
  42393. // Get a reference to the array of objects with queries. The renderContextData property
  42394. // can be changed by another render pass before the async reading of all previous queries complete
  42395. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  42396. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  42397. renderContextData.lastOcclusionObject = null;
  42398. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  42399. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  42400. renderContextData.occlusionQueryIndex = 0;
  42401. }
  42402. }
  42403. /**
  42404. * This method is executed at the end of a render call and finalizes work
  42405. * after draw calls.
  42406. *
  42407. * @param {RenderContext} renderContext - The render context.
  42408. */
  42409. finishRender( renderContext ) {
  42410. const { gl, state } = this;
  42411. const renderContextData = this.get( renderContext );
  42412. const previousContext = renderContextData.previousContext;
  42413. state.resetVertexState();
  42414. const occlusionQueryCount = renderContext.occlusionQueryCount;
  42415. if ( occlusionQueryCount > 0 ) {
  42416. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  42417. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  42418. }
  42419. this.resolveOccludedAsync( renderContext );
  42420. }
  42421. const textures = renderContext.textures;
  42422. if ( textures !== null ) {
  42423. for ( let i = 0; i < textures.length; i ++ ) {
  42424. const texture = textures[ i ];
  42425. if ( texture.generateMipmaps ) {
  42426. this.generateMipmaps( texture );
  42427. }
  42428. }
  42429. }
  42430. this._currentContext = previousContext;
  42431. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  42432. const renderTargetContextData = this.get( renderContext.renderTarget );
  42433. const { samples } = renderContext.renderTarget;
  42434. if ( samples > 0 && this._useMultisampledRTT( renderContext.renderTarget ) === false ) {
  42435. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  42436. const mask = gl.COLOR_BUFFER_BIT;
  42437. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42438. const textures = renderContext.textures;
  42439. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  42440. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42441. for ( let i = 0; i < textures.length; i ++ ) {
  42442. // TODO Add support for MRT
  42443. if ( renderContext.scissor ) {
  42444. const { x, y, width, height } = renderContext.scissorValue;
  42445. const viewY = renderContext.height - height - y;
  42446. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  42447. if ( this._supportsInvalidateFramebuffer === true ) {
  42448. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  42449. }
  42450. } else {
  42451. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  42452. if ( this._supportsInvalidateFramebuffer === true ) {
  42453. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  42454. }
  42455. }
  42456. }
  42457. }
  42458. }
  42459. if ( previousContext !== null ) {
  42460. this._setFramebuffer( previousContext );
  42461. if ( previousContext.viewport ) {
  42462. this.updateViewport( previousContext );
  42463. } else {
  42464. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  42465. }
  42466. }
  42467. this.prepareTimestampBuffer( renderContext );
  42468. }
  42469. /**
  42470. * This method processes the result of occlusion queries and writes it
  42471. * into render context data.
  42472. *
  42473. * @async
  42474. * @param {RenderContext} renderContext - The render context.
  42475. */
  42476. resolveOccludedAsync( renderContext ) {
  42477. const renderContextData = this.get( renderContext );
  42478. // handle occlusion query results
  42479. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  42480. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  42481. const occluded = new WeakSet();
  42482. const { gl } = this;
  42483. renderContextData.currentOcclusionQueryObjects = null;
  42484. renderContextData.currentOcclusionQueries = null;
  42485. const check = () => {
  42486. let completed = 0;
  42487. // check all queries and requeue as appropriate
  42488. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  42489. const query = currentOcclusionQueries[ i ];
  42490. if ( query === null ) continue;
  42491. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  42492. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  42493. currentOcclusionQueries[ i ] = null;
  42494. gl.deleteQuery( query );
  42495. completed ++;
  42496. }
  42497. }
  42498. if ( completed < currentOcclusionQueries.length ) {
  42499. requestAnimationFrame( check );
  42500. } else {
  42501. renderContextData.occluded = occluded;
  42502. }
  42503. };
  42504. check();
  42505. }
  42506. }
  42507. /**
  42508. * Returns `true` if the given 3D object is fully occluded by other
  42509. * 3D objects in the scene.
  42510. *
  42511. * @param {RenderContext} renderContext - The render context.
  42512. * @param {Object3D} object - The 3D object to test.
  42513. * @return {boolean} Whether the 3D object is fully occluded or not.
  42514. */
  42515. isOccluded( renderContext, object ) {
  42516. const renderContextData = this.get( renderContext );
  42517. return renderContextData.occluded && renderContextData.occluded.has( object );
  42518. }
  42519. /**
  42520. * Updates the viewport with the values from the given render context.
  42521. *
  42522. * @param {RenderContext} renderContext - The render context.
  42523. */
  42524. updateViewport( renderContext ) {
  42525. const { state } = this;
  42526. const { x, y, width, height } = renderContext.viewportValue;
  42527. state.viewport( x, renderContext.height - height - y, width, height );
  42528. }
  42529. /**
  42530. * Defines the scissor test.
  42531. *
  42532. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42533. */
  42534. setScissorTest( boolean ) {
  42535. const state = this.state;
  42536. state.setScissorTest( boolean );
  42537. }
  42538. /**
  42539. * Returns the clear color and alpha into a single
  42540. * color object.
  42541. *
  42542. * @return {Color4} The clear color.
  42543. */
  42544. getClearColor() {
  42545. const clearColor = super.getClearColor();
  42546. // Since the canvas is always created with alpha: true,
  42547. // WebGL must always premultiply the clear color.
  42548. clearColor.r *= clearColor.a;
  42549. clearColor.g *= clearColor.a;
  42550. clearColor.b *= clearColor.a;
  42551. return clearColor;
  42552. }
  42553. /**
  42554. * Performs a clear operation.
  42555. *
  42556. * @param {boolean} color - Whether the color buffer should be cleared or not.
  42557. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  42558. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  42559. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  42560. * @param {boolean} [setFrameBuffer=true] - TODO.
  42561. */
  42562. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  42563. const { gl, renderer } = this;
  42564. if ( descriptor === null ) {
  42565. const clearColor = this.getClearColor();
  42566. descriptor = {
  42567. textures: null,
  42568. clearColorValue: clearColor
  42569. };
  42570. }
  42571. //
  42572. let clear = 0;
  42573. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  42574. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  42575. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  42576. if ( clear !== 0 ) {
  42577. let clearColor;
  42578. if ( descriptor.clearColorValue ) {
  42579. clearColor = descriptor.clearColorValue;
  42580. } else {
  42581. clearColor = this.getClearColor();
  42582. }
  42583. const clearDepth = renderer.getClearDepth();
  42584. const clearStencil = renderer.getClearStencil();
  42585. if ( depth ) this.state.setDepthMask( true );
  42586. if ( descriptor.textures === null ) {
  42587. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  42588. gl.clear( clear );
  42589. } else {
  42590. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  42591. if ( color ) {
  42592. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  42593. if ( i === 0 ) {
  42594. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  42595. } else {
  42596. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  42597. }
  42598. }
  42599. }
  42600. if ( depth && stencil ) {
  42601. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  42602. } else if ( depth ) {
  42603. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  42604. } else if ( stencil ) {
  42605. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  42606. }
  42607. }
  42608. }
  42609. }
  42610. /**
  42611. * This method is executed at the beginning of a compute call and
  42612. * prepares the state for upcoming compute tasks.
  42613. *
  42614. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42615. */
  42616. beginCompute( computeGroup ) {
  42617. const { state, gl } = this;
  42618. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  42619. this.initTimestampQuery( computeGroup );
  42620. }
  42621. /**
  42622. * Executes a compute command for the given compute node.
  42623. *
  42624. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  42625. * @param {Node} computeNode - The compute node.
  42626. * @param {Array<BindGroup>} bindings - The bindings.
  42627. * @param {ComputePipeline} pipeline - The compute pipeline.
  42628. */
  42629. compute( computeGroup, computeNode, bindings, pipeline ) {
  42630. const { state, gl } = this;
  42631. if ( this.discard === false ) {
  42632. // required here to handle async behaviour of render.compute()
  42633. gl.enable( gl.RASTERIZER_DISCARD );
  42634. this.discard = true;
  42635. }
  42636. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  42637. const vaoKey = this._getVaoKey( attributes );
  42638. const vaoGPU = this.vaoCache[ vaoKey ];
  42639. if ( vaoGPU === undefined ) {
  42640. this._createVao( attributes );
  42641. } else {
  42642. state.setVertexState( vaoGPU );
  42643. }
  42644. state.useProgram( programGPU );
  42645. this._bindUniforms( bindings );
  42646. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  42647. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  42648. gl.beginTransformFeedback( gl.POINTS );
  42649. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  42650. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  42651. } else {
  42652. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  42653. }
  42654. gl.endTransformFeedback();
  42655. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  42656. // switch active buffers
  42657. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  42658. const dualAttributeData = transformBuffers[ i ];
  42659. if ( dualAttributeData.pbo ) {
  42660. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  42661. }
  42662. dualAttributeData.switchBuffers();
  42663. }
  42664. }
  42665. /**
  42666. * This method is executed at the end of a compute call and
  42667. * finalizes work after compute tasks.
  42668. *
  42669. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42670. */
  42671. finishCompute( computeGroup ) {
  42672. const gl = this.gl;
  42673. this.discard = false;
  42674. gl.disable( gl.RASTERIZER_DISCARD );
  42675. this.prepareTimestampBuffer( computeGroup );
  42676. if ( this._currentContext ) {
  42677. this._setFramebuffer( this._currentContext );
  42678. }
  42679. }
  42680. /**
  42681. * Executes a draw command for the given render object.
  42682. *
  42683. * @param {RenderObject} renderObject - The render object to draw.
  42684. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  42685. */
  42686. draw( renderObject/*, info*/ ) {
  42687. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  42688. const { programGPU } = this.get( pipeline );
  42689. const { gl, state } = this;
  42690. const contextData = this.get( context );
  42691. const drawParams = renderObject.getDrawParameters();
  42692. if ( drawParams === null ) return;
  42693. //
  42694. this._bindUniforms( renderObject.getBindings() );
  42695. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  42696. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  42697. state.useProgram( programGPU );
  42698. // vertex state
  42699. const renderObjectData = this.get( renderObject );
  42700. let vaoGPU = renderObjectData.staticVao;
  42701. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  42702. const vaoKey = this._getVaoKey( renderObject.getAttributes() );
  42703. vaoGPU = this.vaoCache[ vaoKey ];
  42704. if ( vaoGPU === undefined ) {
  42705. let staticVao;
  42706. ( { vaoGPU, staticVao } = this._createVao( renderObject.getAttributes() ) );
  42707. if ( staticVao ) {
  42708. renderObjectData.staticVao = vaoGPU;
  42709. renderObjectData.geometryId = renderObject.geometry.id;
  42710. }
  42711. }
  42712. }
  42713. const index = renderObject.getIndex();
  42714. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  42715. state.setVertexState( vaoGPU, indexGPU );
  42716. //
  42717. const lastObject = contextData.lastOcclusionObject;
  42718. if ( lastObject !== object && lastObject !== undefined ) {
  42719. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  42720. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  42721. contextData.occlusionQueryIndex ++;
  42722. }
  42723. if ( object.occlusionTest === true ) {
  42724. const query = gl.createQuery();
  42725. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  42726. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  42727. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  42728. }
  42729. contextData.lastOcclusionObject = object;
  42730. }
  42731. //
  42732. const renderer = this.bufferRenderer;
  42733. if ( object.isPoints ) renderer.mode = gl.POINTS;
  42734. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  42735. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  42736. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  42737. else {
  42738. if ( material.wireframe === true ) {
  42739. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  42740. renderer.mode = gl.LINES;
  42741. } else {
  42742. renderer.mode = gl.TRIANGLES;
  42743. }
  42744. }
  42745. //
  42746. const { vertexCount, instanceCount } = drawParams;
  42747. let { firstVertex } = drawParams;
  42748. renderer.object = object;
  42749. if ( index !== null ) {
  42750. firstVertex *= index.array.BYTES_PER_ELEMENT;
  42751. const indexData = this.get( index );
  42752. renderer.index = index.count;
  42753. renderer.type = indexData.type;
  42754. } else {
  42755. renderer.index = 0;
  42756. }
  42757. const draw = () => {
  42758. if ( object.isBatchedMesh ) {
  42759. if ( object._multiDrawInstances !== null ) {
  42760. // @deprecated, r174
  42761. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  42762. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  42763. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  42764. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  42765. } else {
  42766. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  42767. }
  42768. } else if ( instanceCount > 1 ) {
  42769. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  42770. } else {
  42771. renderer.render( firstVertex, vertexCount );
  42772. }
  42773. };
  42774. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  42775. const cameraData = this.get( renderObject.camera );
  42776. const cameras = renderObject.camera.cameras;
  42777. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  42778. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  42779. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  42780. const indexesGPU = [];
  42781. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  42782. const bufferGPU = gl.createBuffer();
  42783. data[ 0 ] = i;
  42784. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  42785. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  42786. indexesGPU.push( bufferGPU );
  42787. }
  42788. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  42789. }
  42790. const cameraIndexData = this.get( cameraIndex );
  42791. const pixelRatio = this.renderer.getPixelRatio();
  42792. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  42793. const subCamera = cameras[ i ];
  42794. if ( object.layers.test( subCamera.layers ) ) {
  42795. const vp = subCamera.viewport;
  42796. const x = vp.x * pixelRatio;
  42797. const y = vp.y * pixelRatio;
  42798. const width = vp.width * pixelRatio;
  42799. const height = vp.height * pixelRatio;
  42800. state.viewport(
  42801. Math.floor( x ),
  42802. Math.floor( renderObject.context.height - height - y ),
  42803. Math.floor( width ),
  42804. Math.floor( height )
  42805. );
  42806. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  42807. draw();
  42808. }
  42809. }
  42810. } else {
  42811. draw();
  42812. }
  42813. }
  42814. /**
  42815. * Explain why always null is returned.
  42816. *
  42817. * @param {RenderObject} renderObject - The render object.
  42818. * @return {boolean} Whether the render pipeline requires an update or not.
  42819. */
  42820. needsRenderUpdate( /*renderObject*/ ) {
  42821. return false;
  42822. }
  42823. /**
  42824. * Explain why no cache key is computed.
  42825. *
  42826. * @param {RenderObject} renderObject - The render object.
  42827. * @return {string} The cache key.
  42828. */
  42829. getRenderCacheKey( /*renderObject*/ ) {
  42830. return '';
  42831. }
  42832. // textures
  42833. /**
  42834. * Creates a default texture for the given texture that can be used
  42835. * as a placeholder until the actual texture is ready for usage.
  42836. *
  42837. * @param {Texture} texture - The texture to create a default texture for.
  42838. */
  42839. createDefaultTexture( texture ) {
  42840. this.textureUtils.createDefaultTexture( texture );
  42841. }
  42842. /**
  42843. * Defines a texture on the GPU for the given texture object.
  42844. *
  42845. * @param {Texture} texture - The texture.
  42846. * @param {Object} [options={}] - Optional configuration parameter.
  42847. */
  42848. createTexture( texture, options ) {
  42849. this.textureUtils.createTexture( texture, options );
  42850. }
  42851. /**
  42852. * Uploads the updated texture data to the GPU.
  42853. *
  42854. * @param {Texture} texture - The texture.
  42855. * @param {Object} [options={}] - Optional configuration parameter.
  42856. */
  42857. updateTexture( texture, options ) {
  42858. this.textureUtils.updateTexture( texture, options );
  42859. }
  42860. /**
  42861. * Generates mipmaps for the given texture.
  42862. *
  42863. * @param {Texture} texture - The texture.
  42864. */
  42865. generateMipmaps( texture ) {
  42866. this.textureUtils.generateMipmaps( texture );
  42867. }
  42868. /**
  42869. * Destroys the GPU data for the given texture object.
  42870. *
  42871. * @param {Texture} texture - The texture.
  42872. */
  42873. destroyTexture( texture ) {
  42874. this.textureUtils.destroyTexture( texture );
  42875. }
  42876. /**
  42877. * Returns texture data as a typed array.
  42878. *
  42879. * @async
  42880. * @param {Texture} texture - The texture to copy.
  42881. * @param {number} x - The x coordinate of the copy origin.
  42882. * @param {number} y - The y coordinate of the copy origin.
  42883. * @param {number} width - The width of the copy.
  42884. * @param {number} height - The height of the copy.
  42885. * @param {number} faceIndex - The face index.
  42886. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42887. */
  42888. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42889. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  42890. }
  42891. /**
  42892. * This method does nothing since WebGL 2 has no concept of samplers.
  42893. *
  42894. * @param {Texture} texture - The texture to create the sampler for.
  42895. */
  42896. createSampler( /*texture*/ ) {
  42897. //console.warn( 'Abstract class.' );
  42898. }
  42899. /**
  42900. * This method does nothing since WebGL 2 has no concept of samplers.
  42901. *
  42902. * @param {Texture} texture - The texture to destroy the sampler for.
  42903. */
  42904. destroySampler( /*texture*/ ) {}
  42905. // node builder
  42906. /**
  42907. * Returns a node builder for the given render object.
  42908. *
  42909. * @param {RenderObject} object - The render object.
  42910. * @param {Renderer} renderer - The renderer.
  42911. * @return {GLSLNodeBuilder} The node builder.
  42912. */
  42913. createNodeBuilder( object, renderer ) {
  42914. return new GLSLNodeBuilder( object, renderer );
  42915. }
  42916. // program
  42917. /**
  42918. * Creates a shader program from the given programmable stage.
  42919. *
  42920. * @param {ProgrammableStage} program - The programmable stage.
  42921. */
  42922. createProgram( program ) {
  42923. const gl = this.gl;
  42924. const { stage, code } = program;
  42925. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  42926. gl.shaderSource( shader, code );
  42927. gl.compileShader( shader );
  42928. this.set( program, {
  42929. shaderGPU: shader
  42930. } );
  42931. }
  42932. /**
  42933. * Destroys the shader program of the given programmable stage.
  42934. *
  42935. * @param {ProgrammableStage} program - The programmable stage.
  42936. */
  42937. destroyProgram( program ) {
  42938. this.delete( program );
  42939. }
  42940. /**
  42941. * Creates a render pipeline for the given render object.
  42942. *
  42943. * @param {RenderObject} renderObject - The render object.
  42944. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  42945. */
  42946. createRenderPipeline( renderObject, promises ) {
  42947. const gl = this.gl;
  42948. const pipeline = renderObject.pipeline;
  42949. // Program
  42950. const { fragmentProgram, vertexProgram } = pipeline;
  42951. const programGPU = gl.createProgram();
  42952. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  42953. const vertexShader = this.get( vertexProgram ).shaderGPU;
  42954. gl.attachShader( programGPU, fragmentShader );
  42955. gl.attachShader( programGPU, vertexShader );
  42956. gl.linkProgram( programGPU );
  42957. this.set( pipeline, {
  42958. programGPU,
  42959. fragmentShader,
  42960. vertexShader
  42961. } );
  42962. if ( promises !== null && this.parallel ) {
  42963. const p = new Promise( ( resolve /*, reject*/ ) => {
  42964. const parallel = this.parallel;
  42965. const checkStatus = () => {
  42966. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  42967. this._completeCompile( renderObject, pipeline );
  42968. resolve();
  42969. } else {
  42970. requestAnimationFrame( checkStatus );
  42971. }
  42972. };
  42973. checkStatus();
  42974. } );
  42975. promises.push( p );
  42976. return;
  42977. }
  42978. this._completeCompile( renderObject, pipeline );
  42979. }
  42980. /**
  42981. * Formats the source code of error messages.
  42982. *
  42983. * @private
  42984. * @param {string} string - The code.
  42985. * @param {number} errorLine - The error line.
  42986. * @return {string} The formatted code.
  42987. */
  42988. _handleSource( string, errorLine ) {
  42989. const lines = string.split( '\n' );
  42990. const lines2 = [];
  42991. const from = Math.max( errorLine - 6, 0 );
  42992. const to = Math.min( errorLine + 6, lines.length );
  42993. for ( let i = from; i < to; i ++ ) {
  42994. const line = i + 1;
  42995. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  42996. }
  42997. return lines2.join( '\n' );
  42998. }
  42999. /**
  43000. * Gets the shader compilation errors from the info log.
  43001. *
  43002. * @private
  43003. * @param {WebGL2RenderingContext} gl - The rendering context.
  43004. * @param {WebGLShader} shader - The WebGL shader object.
  43005. * @param {string} type - The shader type.
  43006. * @return {string} The shader errors.
  43007. */
  43008. _getShaderErrors( gl, shader, type ) {
  43009. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  43010. const errors = gl.getShaderInfoLog( shader ).trim();
  43011. if ( status && errors === '' ) return '';
  43012. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  43013. if ( errorMatches ) {
  43014. const errorLine = parseInt( errorMatches[ 1 ] );
  43015. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  43016. } else {
  43017. return errors;
  43018. }
  43019. }
  43020. /**
  43021. * Logs shader compilation errors.
  43022. *
  43023. * @private
  43024. * @param {WebGLProgram} programGPU - The WebGL program.
  43025. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  43026. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  43027. */
  43028. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  43029. if ( this.renderer.debug.checkShaderErrors ) {
  43030. const gl = this.gl;
  43031. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  43032. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  43033. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  43034. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  43035. } else {
  43036. // default error reporting
  43037. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  43038. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  43039. console.error(
  43040. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  43041. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  43042. 'Program Info Log: ' + programLog + '\n' +
  43043. vertexErrors + '\n' +
  43044. fragmentErrors
  43045. );
  43046. }
  43047. } else if ( programLog !== '' ) {
  43048. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  43049. }
  43050. }
  43051. }
  43052. /**
  43053. * Completes the shader program setup for the given render object.
  43054. *
  43055. * @private
  43056. * @param {RenderObject} renderObject - The render object.
  43057. * @param {RenderPipeline} pipeline - The render pipeline.
  43058. */
  43059. _completeCompile( renderObject, pipeline ) {
  43060. const { state, gl } = this;
  43061. const pipelineData = this.get( pipeline );
  43062. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  43063. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  43064. this._logProgramError( programGPU, fragmentShader, vertexShader );
  43065. }
  43066. state.useProgram( programGPU );
  43067. // Bindings
  43068. const bindings = renderObject.getBindings();
  43069. this._setupBindings( bindings, programGPU );
  43070. //
  43071. this.set( pipeline, {
  43072. programGPU
  43073. } );
  43074. }
  43075. /**
  43076. * Creates a compute pipeline for the given compute node.
  43077. *
  43078. * @param {ComputePipeline} computePipeline - The compute pipeline.
  43079. * @param {Array<BindGroup>} bindings - The bindings.
  43080. */
  43081. createComputePipeline( computePipeline, bindings ) {
  43082. const { state, gl } = this;
  43083. // Program
  43084. const fragmentProgram = {
  43085. stage: 'fragment',
  43086. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  43087. };
  43088. this.createProgram( fragmentProgram );
  43089. const { computeProgram } = computePipeline;
  43090. const programGPU = gl.createProgram();
  43091. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  43092. const vertexShader = this.get( computeProgram ).shaderGPU;
  43093. const transforms = computeProgram.transforms;
  43094. const transformVaryingNames = [];
  43095. const transformAttributeNodes = [];
  43096. for ( let i = 0; i < transforms.length; i ++ ) {
  43097. const transform = transforms[ i ];
  43098. transformVaryingNames.push( transform.varyingName );
  43099. transformAttributeNodes.push( transform.attributeNode );
  43100. }
  43101. gl.attachShader( programGPU, fragmentShader );
  43102. gl.attachShader( programGPU, vertexShader );
  43103. gl.transformFeedbackVaryings(
  43104. programGPU,
  43105. transformVaryingNames,
  43106. gl.SEPARATE_ATTRIBS
  43107. );
  43108. gl.linkProgram( programGPU );
  43109. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  43110. this._logProgramError( programGPU, fragmentShader, vertexShader );
  43111. }
  43112. state.useProgram( programGPU );
  43113. // Bindings
  43114. this._setupBindings( bindings, programGPU );
  43115. const attributeNodes = computeProgram.attributes;
  43116. const attributes = [];
  43117. const transformBuffers = [];
  43118. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  43119. const attribute = attributeNodes[ i ].node.attribute;
  43120. attributes.push( attribute );
  43121. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  43122. }
  43123. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  43124. const attribute = transformAttributeNodes[ i ].attribute;
  43125. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  43126. const attributeData = this.get( attribute );
  43127. transformBuffers.push( attributeData );
  43128. }
  43129. //
  43130. this.set( computePipeline, {
  43131. programGPU,
  43132. transformBuffers,
  43133. attributes
  43134. } );
  43135. }
  43136. /**
  43137. * Creates bindings from the given bind group definition.
  43138. *
  43139. * @param {BindGroup} bindGroup - The bind group.
  43140. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43141. * @param {number} cacheIndex - The cache index.
  43142. * @param {number} version - The version.
  43143. */
  43144. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  43145. if ( this._knownBindings.has( bindings ) === false ) {
  43146. this._knownBindings.add( bindings );
  43147. let uniformBuffers = 0;
  43148. let textures = 0;
  43149. for ( const bindGroup of bindings ) {
  43150. this.set( bindGroup, {
  43151. textures: textures,
  43152. uniformBuffers: uniformBuffers
  43153. } );
  43154. for ( const binding of bindGroup.bindings ) {
  43155. if ( binding.isUniformBuffer ) uniformBuffers ++;
  43156. if ( binding.isSampledTexture ) textures ++;
  43157. }
  43158. }
  43159. }
  43160. this.updateBindings( bindGroup, bindings );
  43161. }
  43162. /**
  43163. * Updates the given bind group definition.
  43164. *
  43165. * @param {BindGroup} bindGroup - The bind group.
  43166. * @param {Array<BindGroup>} bindings - Array of bind groups.
  43167. * @param {number} cacheIndex - The cache index.
  43168. * @param {number} version - The version.
  43169. */
  43170. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  43171. const { gl } = this;
  43172. const bindGroupData = this.get( bindGroup );
  43173. let i = bindGroupData.uniformBuffers;
  43174. let t = bindGroupData.textures;
  43175. for ( const binding of bindGroup.bindings ) {
  43176. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  43177. const data = binding.buffer;
  43178. const bufferGPU = gl.createBuffer();
  43179. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  43180. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  43181. this.set( binding, {
  43182. index: i ++,
  43183. bufferGPU
  43184. } );
  43185. } else if ( binding.isSampledTexture ) {
  43186. const { textureGPU, glTextureType } = this.get( binding.texture );
  43187. this.set( binding, {
  43188. index: t ++,
  43189. textureGPU,
  43190. glTextureType
  43191. } );
  43192. }
  43193. }
  43194. }
  43195. /**
  43196. * Updates a buffer binding.
  43197. *
  43198. * @param {Buffer} binding - The buffer binding to update.
  43199. */
  43200. updateBinding( binding ) {
  43201. const gl = this.gl;
  43202. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  43203. const bindingData = this.get( binding );
  43204. const bufferGPU = bindingData.bufferGPU;
  43205. const data = binding.buffer;
  43206. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  43207. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  43208. }
  43209. }
  43210. // attributes
  43211. /**
  43212. * Creates the GPU buffer of an indexed shader attribute.
  43213. *
  43214. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  43215. */
  43216. createIndexAttribute( attribute ) {
  43217. const gl = this.gl;
  43218. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  43219. }
  43220. /**
  43221. * Creates the GPU buffer of a shader attribute.
  43222. *
  43223. * @param {BufferAttribute} attribute - The buffer attribute.
  43224. */
  43225. createAttribute( attribute ) {
  43226. if ( this.has( attribute ) ) return;
  43227. const gl = this.gl;
  43228. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  43229. }
  43230. /**
  43231. * Creates the GPU buffer of a storage attribute.
  43232. *
  43233. * @param {BufferAttribute} attribute - The buffer attribute.
  43234. */
  43235. createStorageAttribute( attribute ) {
  43236. if ( this.has( attribute ) ) return;
  43237. const gl = this.gl;
  43238. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  43239. }
  43240. /**
  43241. * Updates the GPU buffer of a shader attribute.
  43242. *
  43243. * @param {BufferAttribute} attribute - The buffer attribute to update.
  43244. */
  43245. updateAttribute( attribute ) {
  43246. this.attributeUtils.updateAttribute( attribute );
  43247. }
  43248. /**
  43249. * Destroys the GPU buffer of a shader attribute.
  43250. *
  43251. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  43252. */
  43253. destroyAttribute( attribute ) {
  43254. this.attributeUtils.destroyAttribute( attribute );
  43255. }
  43256. /**
  43257. * Checks if the given feature is supported by the backend.
  43258. *
  43259. * @param {string} name - The feature's name.
  43260. * @return {boolean} Whether the feature is supported or not.
  43261. */
  43262. hasFeature( name ) {
  43263. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  43264. const extensions = this.extensions;
  43265. for ( let i = 0; i < keysMatching.length; i ++ ) {
  43266. if ( extensions.has( keysMatching[ i ] ) ) return true;
  43267. }
  43268. return false;
  43269. }
  43270. /**
  43271. * Returns the maximum anisotropy texture filtering value.
  43272. *
  43273. * @return {number} The maximum anisotropy texture filtering value.
  43274. */
  43275. getMaxAnisotropy() {
  43276. return this.capabilities.getMaxAnisotropy();
  43277. }
  43278. /**
  43279. * Copies data of the given source texture to the given destination texture.
  43280. *
  43281. * @param {Texture} srcTexture - The source texture.
  43282. * @param {Texture} dstTexture - The destination texture.
  43283. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  43284. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  43285. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43286. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43287. */
  43288. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  43289. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  43290. }
  43291. /**
  43292. * Copies the current bound framebuffer to the given texture.
  43293. *
  43294. * @param {Texture} texture - The destination texture.
  43295. * @param {RenderContext} renderContext - The render context.
  43296. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43297. */
  43298. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  43299. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  43300. }
  43301. /**
  43302. * Configures the active framebuffer from the given render context.
  43303. *
  43304. * @private
  43305. * @param {RenderContext} descriptor - The render context.
  43306. */
  43307. _setFramebuffer( descriptor ) {
  43308. const { gl, state } = this;
  43309. let currentFrameBuffer = null;
  43310. if ( descriptor.textures !== null ) {
  43311. const renderTarget = descriptor.renderTarget;
  43312. const renderTargetContextData = this.get( renderTarget );
  43313. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  43314. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  43315. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  43316. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  43317. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  43318. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  43319. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  43320. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  43321. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43322. const useMultisampledRTT = this._useMultisampledRTT( renderTarget );
  43323. const cacheKey = getCacheKey( descriptor );
  43324. let fb;
  43325. if ( isCube ) {
  43326. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  43327. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  43328. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  43329. fb = this._xrFramebuffer;
  43330. } else {
  43331. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  43332. fb = renderTargetContextData.framebuffers[ cacheKey ];
  43333. }
  43334. if ( fb === undefined ) {
  43335. fb = gl.createFramebuffer();
  43336. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  43337. const textures = descriptor.textures;
  43338. if ( isCube ) {
  43339. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  43340. const { textureGPU } = this.get( textures[ 0 ] );
  43341. const cubeFace = this.renderer._activeCubeFace;
  43342. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  43343. } else {
  43344. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  43345. for ( let i = 0; i < textures.length; i ++ ) {
  43346. const texture = textures[ i ];
  43347. const textureData = this.get( texture );
  43348. textureData.renderTarget = descriptor.renderTarget;
  43349. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  43350. const attachment = gl.COLOR_ATTACHMENT0 + i;
  43351. if ( isRenderTarget3D || isRenderTargetArray ) {
  43352. const layer = this.renderer._activeCubeFace;
  43353. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  43354. } else {
  43355. if ( hasExternalTextures && useMultisampledRTT ) {
  43356. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  43357. } else {
  43358. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  43359. }
  43360. }
  43361. }
  43362. state.drawBuffers( descriptor, fb );
  43363. }
  43364. if ( renderTarget.isXRRenderTarget && renderTarget.autoAllocateDepthBuffer === true ) {
  43365. const renderbuffer = gl.createRenderbuffer();
  43366. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  43367. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  43368. } else {
  43369. if ( descriptor.depthTexture !== null ) {
  43370. const textureData = this.get( descriptor.depthTexture );
  43371. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  43372. textureData.renderTarget = descriptor.renderTarget;
  43373. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  43374. if ( hasExternalTextures && useMultisampledRTT ) {
  43375. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  43376. } else {
  43377. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  43378. }
  43379. }
  43380. }
  43381. } else {
  43382. // rebind external XR textures
  43383. if ( isXRRenderTarget && hasExternalTextures ) {
  43384. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  43385. // rebind color
  43386. const textureData = this.get( descriptor.textures[ 0 ] );
  43387. if ( useMultisampledRTT ) {
  43388. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  43389. } else {
  43390. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  43391. }
  43392. // rebind depth
  43393. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  43394. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  43395. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  43396. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  43397. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  43398. } else {
  43399. const textureData = this.get( descriptor.depthTexture );
  43400. if ( useMultisampledRTT ) {
  43401. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  43402. } else {
  43403. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  43404. }
  43405. }
  43406. }
  43407. }
  43408. if ( samples > 0 && useMultisampledRTT === false ) {
  43409. if ( msaaFb === undefined ) {
  43410. const invalidationArray = [];
  43411. msaaFb = gl.createFramebuffer();
  43412. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  43413. const msaaRenderbuffers = [];
  43414. const textures = descriptor.textures;
  43415. for ( let i = 0; i < textures.length; i ++ ) {
  43416. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  43417. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  43418. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  43419. if ( depthBuffer ) {
  43420. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  43421. invalidationArray.push( depthStyle );
  43422. }
  43423. const texture = descriptor.textures[ i ];
  43424. const textureData = this.get( texture );
  43425. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  43426. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  43427. }
  43428. renderTargetContextData.msaaFrameBuffer = msaaFb;
  43429. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  43430. if ( depthRenderbuffer === undefined ) {
  43431. depthRenderbuffer = gl.createRenderbuffer();
  43432. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  43433. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  43434. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  43435. invalidationArray.push( depthStyle );
  43436. }
  43437. renderTargetContextData.invalidationArray = invalidationArray;
  43438. }
  43439. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43440. } else {
  43441. currentFrameBuffer = fb;
  43442. }
  43443. }
  43444. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  43445. }
  43446. /**
  43447. * Computes the VAO key for the given index and attributes.
  43448. *
  43449. * @private
  43450. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  43451. * @return {string} The VAO key.
  43452. */
  43453. _getVaoKey( attributes ) {
  43454. let key = '';
  43455. for ( let i = 0; i < attributes.length; i ++ ) {
  43456. const attributeData = this.get( attributes[ i ] );
  43457. key += ':' + attributeData.id;
  43458. }
  43459. return key;
  43460. }
  43461. /**
  43462. * Creates a VAO from the index and attributes.
  43463. *
  43464. * @private
  43465. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  43466. * @return {Object} The VAO data.
  43467. */
  43468. _createVao( attributes ) {
  43469. const { gl } = this;
  43470. const vaoGPU = gl.createVertexArray();
  43471. let key = '';
  43472. let staticVao = true;
  43473. gl.bindVertexArray( vaoGPU );
  43474. for ( let i = 0; i < attributes.length; i ++ ) {
  43475. const attribute = attributes[ i ];
  43476. const attributeData = this.get( attribute );
  43477. key += ':' + attributeData.id;
  43478. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  43479. gl.enableVertexAttribArray( i );
  43480. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  43481. let stride, offset;
  43482. if ( attribute.isInterleavedBufferAttribute === true ) {
  43483. stride = attribute.data.stride * attributeData.bytesPerElement;
  43484. offset = attribute.offset * attributeData.bytesPerElement;
  43485. } else {
  43486. stride = 0;
  43487. offset = 0;
  43488. }
  43489. if ( attributeData.isInteger ) {
  43490. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  43491. } else {
  43492. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  43493. }
  43494. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  43495. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  43496. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  43497. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  43498. }
  43499. }
  43500. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  43501. this.vaoCache[ key ] = vaoGPU;
  43502. return { vaoGPU, staticVao };
  43503. }
  43504. /**
  43505. * Creates a transform feedback from the given transform buffers.
  43506. *
  43507. * @private
  43508. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  43509. * @return {WebGLTransformFeedback} The transform feedback.
  43510. */
  43511. _getTransformFeedback( transformBuffers ) {
  43512. let key = '';
  43513. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  43514. key += ':' + transformBuffers[ i ].id;
  43515. }
  43516. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  43517. if ( transformFeedbackGPU !== undefined ) {
  43518. return transformFeedbackGPU;
  43519. }
  43520. const { gl } = this;
  43521. transformFeedbackGPU = gl.createTransformFeedback();
  43522. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  43523. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  43524. const attributeData = transformBuffers[ i ];
  43525. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  43526. }
  43527. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  43528. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  43529. return transformFeedbackGPU;
  43530. }
  43531. /**
  43532. * Setups the given bindings.
  43533. *
  43534. * @private
  43535. * @param {Array<BindGroup>} bindings - The bindings.
  43536. * @param {WebGLProgram} programGPU - The WebGL program.
  43537. */
  43538. _setupBindings( bindings, programGPU ) {
  43539. const gl = this.gl;
  43540. for ( const bindGroup of bindings ) {
  43541. for ( const binding of bindGroup.bindings ) {
  43542. const bindingData = this.get( binding );
  43543. const index = bindingData.index;
  43544. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  43545. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  43546. gl.uniformBlockBinding( programGPU, location, index );
  43547. } else if ( binding.isSampledTexture ) {
  43548. const location = gl.getUniformLocation( programGPU, binding.name );
  43549. gl.uniform1i( location, index );
  43550. }
  43551. }
  43552. }
  43553. }
  43554. /**
  43555. * Binds the given uniforms.
  43556. *
  43557. * @private
  43558. * @param {Array<BindGroup>} bindings - The bindings.
  43559. */
  43560. _bindUniforms( bindings ) {
  43561. const { gl, state } = this;
  43562. for ( const bindGroup of bindings ) {
  43563. for ( const binding of bindGroup.bindings ) {
  43564. const bindingData = this.get( binding );
  43565. const index = bindingData.index;
  43566. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  43567. // TODO USE bindBufferRange to group multiple uniform buffers
  43568. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  43569. } else if ( binding.isSampledTexture ) {
  43570. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  43571. }
  43572. }
  43573. }
  43574. }
  43575. /**
  43576. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  43577. * should be used when MSAA is enabled.
  43578. *
  43579. * @private
  43580. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  43581. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  43582. */
  43583. _useMultisampledRTT( renderTarget ) {
  43584. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget.autoAllocateDepthBuffer !== false;
  43585. }
  43586. /**
  43587. * Frees internal resources.
  43588. */
  43589. dispose() {
  43590. const extension = this.extensions.get( 'WEBGL_lose_context' );
  43591. if ( extension ) extension.loseContext();
  43592. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  43593. }
  43594. }
  43595. const GPUPrimitiveTopology = {
  43596. PointList: 'point-list',
  43597. LineList: 'line-list',
  43598. LineStrip: 'line-strip',
  43599. TriangleList: 'triangle-list',
  43600. TriangleStrip: 'triangle-strip',
  43601. };
  43602. const GPUCompareFunction = {
  43603. Never: 'never',
  43604. Less: 'less',
  43605. Equal: 'equal',
  43606. LessEqual: 'less-equal',
  43607. Greater: 'greater',
  43608. NotEqual: 'not-equal',
  43609. GreaterEqual: 'greater-equal',
  43610. Always: 'always'
  43611. };
  43612. const GPUStoreOp = {
  43613. Store: 'store'};
  43614. const GPULoadOp = {
  43615. Load: 'load',
  43616. Clear: 'clear'
  43617. };
  43618. const GPUFrontFace = {
  43619. CCW: 'ccw'};
  43620. const GPUCullMode = {
  43621. None: 'none',
  43622. Front: 'front',
  43623. Back: 'back'
  43624. };
  43625. const GPUIndexFormat = {
  43626. Uint16: 'uint16',
  43627. Uint32: 'uint32'
  43628. };
  43629. const GPUTextureFormat = {
  43630. // 8-bit formats
  43631. R8Unorm: 'r8unorm',
  43632. R8Snorm: 'r8snorm',
  43633. R8Uint: 'r8uint',
  43634. R8Sint: 'r8sint',
  43635. // 16-bit formats
  43636. R16Uint: 'r16uint',
  43637. R16Sint: 'r16sint',
  43638. R16Float: 'r16float',
  43639. RG8Unorm: 'rg8unorm',
  43640. RG8Snorm: 'rg8snorm',
  43641. RG8Uint: 'rg8uint',
  43642. RG8Sint: 'rg8sint',
  43643. // 32-bit formats
  43644. R32Uint: 'r32uint',
  43645. R32Sint: 'r32sint',
  43646. R32Float: 'r32float',
  43647. RG16Uint: 'rg16uint',
  43648. RG16Sint: 'rg16sint',
  43649. RG16Float: 'rg16float',
  43650. RGBA8Unorm: 'rgba8unorm',
  43651. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  43652. RGBA8Snorm: 'rgba8snorm',
  43653. RGBA8Uint: 'rgba8uint',
  43654. RGBA8Sint: 'rgba8sint',
  43655. BGRA8Unorm: 'bgra8unorm',
  43656. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  43657. // Packed 32-bit formats
  43658. RGB9E5UFloat: 'rgb9e5ufloat',
  43659. RGB10A2Unorm: 'rgb10a2unorm',
  43660. RG11B10UFloat: 'rgb10a2unorm',
  43661. // 64-bit formats
  43662. RG32Uint: 'rg32uint',
  43663. RG32Sint: 'rg32sint',
  43664. RG32Float: 'rg32float',
  43665. RGBA16Uint: 'rgba16uint',
  43666. RGBA16Sint: 'rgba16sint',
  43667. RGBA16Float: 'rgba16float',
  43668. // 128-bit formats
  43669. RGBA32Uint: 'rgba32uint',
  43670. RGBA32Sint: 'rgba32sint',
  43671. RGBA32Float: 'rgba32float',
  43672. Depth16Unorm: 'depth16unorm',
  43673. Depth24Plus: 'depth24plus',
  43674. Depth24PlusStencil8: 'depth24plus-stencil8',
  43675. Depth32Float: 'depth32float',
  43676. // 'depth32float-stencil8' extension
  43677. Depth32FloatStencil8: 'depth32float-stencil8',
  43678. // BC compressed formats usable if 'texture-compression-bc' is both
  43679. // supported by the device/user agent and enabled in requestDevice.
  43680. BC1RGBAUnorm: 'bc1-rgba-unorm',
  43681. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  43682. BC2RGBAUnorm: 'bc2-rgba-unorm',
  43683. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  43684. BC3RGBAUnorm: 'bc3-rgba-unorm',
  43685. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  43686. BC4RUnorm: 'bc4-r-unorm',
  43687. BC4RSnorm: 'bc4-r-snorm',
  43688. BC5RGUnorm: 'bc5-rg-unorm',
  43689. BC5RGSnorm: 'bc5-rg-snorm',
  43690. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  43691. BC6HRGBFloat: 'bc6h-rgb-float',
  43692. BC7RGBAUnorm: 'bc7-rgba-unorm',
  43693. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  43694. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  43695. // supported by the device/user agent and enabled in requestDevice.
  43696. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  43697. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  43698. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  43699. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  43700. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  43701. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  43702. EACR11Unorm: 'eac-r11unorm',
  43703. EACR11Snorm: 'eac-r11snorm',
  43704. EACRG11Unorm: 'eac-rg11unorm',
  43705. EACRG11Snorm: 'eac-rg11snorm',
  43706. // ASTC compressed formats usable if 'texture-compression-astc' is both
  43707. // supported by the device/user agent and enabled in requestDevice.
  43708. ASTC4x4Unorm: 'astc-4x4-unorm',
  43709. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  43710. ASTC5x4Unorm: 'astc-5x4-unorm',
  43711. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  43712. ASTC5x5Unorm: 'astc-5x5-unorm',
  43713. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  43714. ASTC6x5Unorm: 'astc-6x5-unorm',
  43715. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  43716. ASTC6x6Unorm: 'astc-6x6-unorm',
  43717. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  43718. ASTC8x5Unorm: 'astc-8x5-unorm',
  43719. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  43720. ASTC8x6Unorm: 'astc-8x6-unorm',
  43721. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  43722. ASTC8x8Unorm: 'astc-8x8-unorm',
  43723. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  43724. ASTC10x5Unorm: 'astc-10x5-unorm',
  43725. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  43726. ASTC10x6Unorm: 'astc-10x6-unorm',
  43727. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  43728. ASTC10x8Unorm: 'astc-10x8-unorm',
  43729. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  43730. ASTC10x10Unorm: 'astc-10x10-unorm',
  43731. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  43732. ASTC12x10Unorm: 'astc-12x10-unorm',
  43733. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  43734. ASTC12x12Unorm: 'astc-12x12-unorm',
  43735. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  43736. };
  43737. const GPUAddressMode = {
  43738. ClampToEdge: 'clamp-to-edge',
  43739. Repeat: 'repeat',
  43740. MirrorRepeat: 'mirror-repeat'
  43741. };
  43742. const GPUFilterMode = {
  43743. Linear: 'linear',
  43744. Nearest: 'nearest'
  43745. };
  43746. const GPUBlendFactor = {
  43747. Zero: 'zero',
  43748. One: 'one',
  43749. Src: 'src',
  43750. OneMinusSrc: 'one-minus-src',
  43751. SrcAlpha: 'src-alpha',
  43752. OneMinusSrcAlpha: 'one-minus-src-alpha',
  43753. Dst: 'dst',
  43754. OneMinusDstColor: 'one-minus-dst',
  43755. DstAlpha: 'dst-alpha',
  43756. OneMinusDstAlpha: 'one-minus-dst-alpha',
  43757. SrcAlphaSaturated: 'src-alpha-saturated',
  43758. Constant: 'constant',
  43759. OneMinusConstant: 'one-minus-constant'
  43760. };
  43761. const GPUBlendOperation = {
  43762. Add: 'add',
  43763. Subtract: 'subtract',
  43764. ReverseSubtract: 'reverse-subtract',
  43765. Min: 'min',
  43766. Max: 'max'
  43767. };
  43768. const GPUColorWriteFlags = {
  43769. None: 0,
  43770. All: 0xF
  43771. };
  43772. const GPUStencilOperation = {
  43773. Keep: 'keep',
  43774. Zero: 'zero',
  43775. Replace: 'replace',
  43776. Invert: 'invert',
  43777. IncrementClamp: 'increment-clamp',
  43778. DecrementClamp: 'decrement-clamp',
  43779. IncrementWrap: 'increment-wrap',
  43780. DecrementWrap: 'decrement-wrap'
  43781. };
  43782. const GPUBufferBindingType = {
  43783. Storage: 'storage',
  43784. ReadOnlyStorage: 'read-only-storage'
  43785. };
  43786. const GPUStorageTextureAccess = {
  43787. WriteOnly: 'write-only',
  43788. ReadOnly: 'read-only',
  43789. ReadWrite: 'read-write',
  43790. };
  43791. const GPUTextureSampleType = {
  43792. Float: 'float',
  43793. UnfilterableFloat: 'unfilterable-float',
  43794. Depth: 'depth',
  43795. SInt: 'sint',
  43796. UInt: 'uint'
  43797. };
  43798. const GPUTextureDimension = {
  43799. TwoD: '2d',
  43800. ThreeD: '3d'
  43801. };
  43802. const GPUTextureViewDimension = {
  43803. TwoD: '2d',
  43804. TwoDArray: '2d-array',
  43805. Cube: 'cube',
  43806. ThreeD: '3d'
  43807. };
  43808. const GPUTextureAspect = {
  43809. All: 'all'};
  43810. const GPUInputStepMode = {
  43811. Vertex: 'vertex',
  43812. Instance: 'instance'
  43813. };
  43814. const GPUFeatureName = {
  43815. DepthClipControl: 'depth-clip-control',
  43816. Depth32FloatStencil8: 'depth32float-stencil8',
  43817. TextureCompressionBC: 'texture-compression-bc',
  43818. TextureCompressionETC2: 'texture-compression-etc2',
  43819. TextureCompressionASTC: 'texture-compression-astc',
  43820. TimestampQuery: 'timestamp-query',
  43821. IndirectFirstInstance: 'indirect-first-instance',
  43822. ShaderF16: 'shader-f16',
  43823. RG11B10UFloat: 'rg11b10ufloat-renderable',
  43824. BGRA8UNormStorage: 'bgra8unorm-storage',
  43825. Float32Filterable: 'float32-filterable',
  43826. ClipDistances: 'clip-distances',
  43827. DualSourceBlending: 'dual-source-blending',
  43828. Subgroups: 'subgroups'
  43829. };
  43830. /**
  43831. * Represents a sampler binding type.
  43832. *
  43833. * @private
  43834. * @augments Binding
  43835. */
  43836. class Sampler extends Binding {
  43837. /**
  43838. * Constructs a new sampler.
  43839. *
  43840. * @param {string} name - The samplers's name.
  43841. * @param {?Texture} texture - The texture this binding is referring to.
  43842. */
  43843. constructor( name, texture ) {
  43844. super( name );
  43845. /**
  43846. * The texture the sampler is referring to.
  43847. *
  43848. * @type {?Texture}
  43849. */
  43850. this.texture = texture;
  43851. /**
  43852. * The binding's version.
  43853. *
  43854. * @type {number}
  43855. */
  43856. this.version = texture ? texture.version : 0;
  43857. /**
  43858. * This flag can be used for type testing.
  43859. *
  43860. * @type {boolean}
  43861. * @readonly
  43862. * @default true
  43863. */
  43864. this.isSampler = true;
  43865. }
  43866. }
  43867. /**
  43868. * A special form of sampler binding type.
  43869. * It's texture value is managed by a node object.
  43870. *
  43871. * @private
  43872. * @augments Sampler
  43873. */
  43874. class NodeSampler extends Sampler {
  43875. /**
  43876. * Constructs a new node-based sampler.
  43877. *
  43878. * @param {string} name - The samplers's name.
  43879. * @param {TextureNode} textureNode - The texture node.
  43880. * @param {UniformGroupNode} groupNode - The uniform group node.
  43881. */
  43882. constructor( name, textureNode, groupNode ) {
  43883. super( name, textureNode ? textureNode.value : null );
  43884. /**
  43885. * The texture node.
  43886. *
  43887. * @type {TextureNode}
  43888. */
  43889. this.textureNode = textureNode;
  43890. /**
  43891. * The uniform group node.
  43892. *
  43893. * @type {UniformGroupNode}
  43894. */
  43895. this.groupNode = groupNode;
  43896. }
  43897. /**
  43898. * Updates the texture value of this sampler.
  43899. */
  43900. update() {
  43901. this.texture = this.textureNode.value;
  43902. }
  43903. }
  43904. /**
  43905. * Represents a storage buffer binding type.
  43906. *
  43907. * @private
  43908. * @augments Buffer
  43909. */
  43910. class StorageBuffer extends Buffer {
  43911. /**
  43912. * Constructs a new uniform buffer.
  43913. *
  43914. * @param {string} name - The buffer's name.
  43915. * @param {BufferAttribute} attribute - The buffer attribute.
  43916. */
  43917. constructor( name, attribute ) {
  43918. super( name, attribute ? attribute.array : null );
  43919. /**
  43920. * This flag can be used for type testing.
  43921. *
  43922. * @type {BufferAttribute}
  43923. */
  43924. this.attribute = attribute;
  43925. /**
  43926. * This flag can be used for type testing.
  43927. *
  43928. * @type {boolean}
  43929. * @readonly
  43930. * @default true
  43931. */
  43932. this.isStorageBuffer = true;
  43933. }
  43934. }
  43935. let _id = 0;
  43936. /**
  43937. * A special form of storage buffer binding type.
  43938. * It's buffer value is managed by a node object.
  43939. *
  43940. * @private
  43941. * @augments StorageBuffer
  43942. */
  43943. class NodeStorageBuffer extends StorageBuffer {
  43944. /**
  43945. * Constructs a new node-based storage buffer.
  43946. *
  43947. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  43948. * @param {UniformGroupNode} groupNode - The uniform group node.
  43949. */
  43950. constructor( nodeUniform, groupNode ) {
  43951. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  43952. /**
  43953. * The node uniform.
  43954. *
  43955. * @type {StorageBufferNode}
  43956. */
  43957. this.nodeUniform = nodeUniform;
  43958. /**
  43959. * The access type.
  43960. *
  43961. * @type {string}
  43962. */
  43963. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  43964. /**
  43965. * The uniform group node.
  43966. *
  43967. * @type {UniformGroupNode}
  43968. */
  43969. this.groupNode = groupNode;
  43970. }
  43971. /**
  43972. * The storage buffer.
  43973. *
  43974. * @type {BufferAttribute}
  43975. */
  43976. get buffer() {
  43977. return this.nodeUniform.value;
  43978. }
  43979. }
  43980. /**
  43981. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  43982. *
  43983. * @private
  43984. */
  43985. class WebGPUTexturePassUtils extends DataMap {
  43986. /**
  43987. * Constructs a new utility object.
  43988. *
  43989. * @param {GPUDevice} device - The WebGPU device.
  43990. */
  43991. constructor( device ) {
  43992. super();
  43993. /**
  43994. * The WebGPU device.
  43995. *
  43996. * @type {GPUDevice}
  43997. */
  43998. this.device = device;
  43999. const mipmapVertexSource = `
  44000. struct VarysStruct {
  44001. @builtin( position ) Position: vec4<f32>,
  44002. @location( 0 ) vTex : vec2<f32>
  44003. };
  44004. @vertex
  44005. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  44006. var Varys : VarysStruct;
  44007. var pos = array< vec2<f32>, 4 >(
  44008. vec2<f32>( -1.0, 1.0 ),
  44009. vec2<f32>( 1.0, 1.0 ),
  44010. vec2<f32>( -1.0, -1.0 ),
  44011. vec2<f32>( 1.0, -1.0 )
  44012. );
  44013. var tex = array< vec2<f32>, 4 >(
  44014. vec2<f32>( 0.0, 0.0 ),
  44015. vec2<f32>( 1.0, 0.0 ),
  44016. vec2<f32>( 0.0, 1.0 ),
  44017. vec2<f32>( 1.0, 1.0 )
  44018. );
  44019. Varys.vTex = tex[ vertexIndex ];
  44020. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  44021. return Varys;
  44022. }
  44023. `;
  44024. const mipmapFragmentSource = `
  44025. @group( 0 ) @binding( 0 )
  44026. var imgSampler : sampler;
  44027. @group( 0 ) @binding( 1 )
  44028. var img : texture_2d<f32>;
  44029. @fragment
  44030. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  44031. return textureSample( img, imgSampler, vTex );
  44032. }
  44033. `;
  44034. const flipYFragmentSource = `
  44035. @group( 0 ) @binding( 0 )
  44036. var imgSampler : sampler;
  44037. @group( 0 ) @binding( 1 )
  44038. var img : texture_2d<f32>;
  44039. @fragment
  44040. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  44041. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  44042. }
  44043. `;
  44044. /**
  44045. * The mipmap GPU sampler.
  44046. *
  44047. * @type {GPUSampler}
  44048. */
  44049. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  44050. /**
  44051. * The flipY GPU sampler.
  44052. *
  44053. * @type {GPUSampler}
  44054. */
  44055. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  44056. /**
  44057. * A cache for GPU render pipelines used for copy/transfer passes.
  44058. * Every texture format requires a unique pipeline.
  44059. *
  44060. * @type {Object<string,GPURenderPipeline>}
  44061. */
  44062. this.transferPipelines = {};
  44063. /**
  44064. * A cache for GPU render pipelines used for flipY passes.
  44065. * Every texture format requires a unique pipeline.
  44066. *
  44067. * @type {Object<string,GPURenderPipeline>}
  44068. */
  44069. this.flipYPipelines = {};
  44070. /**
  44071. * The mipmap vertex shader module.
  44072. *
  44073. * @type {GPUShaderModule}
  44074. */
  44075. this.mipmapVertexShaderModule = device.createShaderModule( {
  44076. label: 'mipmapVertex',
  44077. code: mipmapVertexSource
  44078. } );
  44079. /**
  44080. * The mipmap fragment shader module.
  44081. *
  44082. * @type {GPUShaderModule}
  44083. */
  44084. this.mipmapFragmentShaderModule = device.createShaderModule( {
  44085. label: 'mipmapFragment',
  44086. code: mipmapFragmentSource
  44087. } );
  44088. /**
  44089. * The flipY fragment shader module.
  44090. *
  44091. * @type {GPUShaderModule}
  44092. */
  44093. this.flipYFragmentShaderModule = device.createShaderModule( {
  44094. label: 'flipYFragment',
  44095. code: flipYFragmentSource
  44096. } );
  44097. }
  44098. /**
  44099. * Returns a render pipeline for the internal copy render pass. The pass
  44100. * requires a unique render pipeline for each texture format.
  44101. *
  44102. * @param {string} format - The GPU texture format
  44103. * @return {GPURenderPipeline} The GPU render pipeline.
  44104. */
  44105. getTransferPipeline( format ) {
  44106. let pipeline = this.transferPipelines[ format ];
  44107. if ( pipeline === undefined ) {
  44108. pipeline = this.device.createRenderPipeline( {
  44109. label: `mipmap-${ format }`,
  44110. vertex: {
  44111. module: this.mipmapVertexShaderModule,
  44112. entryPoint: 'main'
  44113. },
  44114. fragment: {
  44115. module: this.mipmapFragmentShaderModule,
  44116. entryPoint: 'main',
  44117. targets: [ { format } ]
  44118. },
  44119. primitive: {
  44120. topology: GPUPrimitiveTopology.TriangleStrip,
  44121. stripIndexFormat: GPUIndexFormat.Uint32
  44122. },
  44123. layout: 'auto'
  44124. } );
  44125. this.transferPipelines[ format ] = pipeline;
  44126. }
  44127. return pipeline;
  44128. }
  44129. /**
  44130. * Returns a render pipeline for the flipY render pass. The pass
  44131. * requires a unique render pipeline for each texture format.
  44132. *
  44133. * @param {string} format - The GPU texture format
  44134. * @return {GPURenderPipeline} The GPU render pipeline.
  44135. */
  44136. getFlipYPipeline( format ) {
  44137. let pipeline = this.flipYPipelines[ format ];
  44138. if ( pipeline === undefined ) {
  44139. pipeline = this.device.createRenderPipeline( {
  44140. label: `flipY-${ format }`,
  44141. vertex: {
  44142. module: this.mipmapVertexShaderModule,
  44143. entryPoint: 'main'
  44144. },
  44145. fragment: {
  44146. module: this.flipYFragmentShaderModule,
  44147. entryPoint: 'main',
  44148. targets: [ { format } ]
  44149. },
  44150. primitive: {
  44151. topology: GPUPrimitiveTopology.TriangleStrip,
  44152. stripIndexFormat: GPUIndexFormat.Uint32
  44153. },
  44154. layout: 'auto'
  44155. } );
  44156. this.flipYPipelines[ format ] = pipeline;
  44157. }
  44158. return pipeline;
  44159. }
  44160. /**
  44161. * Flip the contents of the given GPU texture along its vertical axis.
  44162. *
  44163. * @param {GPUTexture} textureGPU - The GPU texture object.
  44164. * @param {Object} textureGPUDescriptor - The texture descriptor.
  44165. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  44166. */
  44167. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  44168. const format = textureGPUDescriptor.format;
  44169. const { width, height } = textureGPUDescriptor.size;
  44170. const transferPipeline = this.getTransferPipeline( format );
  44171. const flipYPipeline = this.getFlipYPipeline( format );
  44172. const tempTexture = this.device.createTexture( {
  44173. size: { width, height, depthOrArrayLayers: 1 },
  44174. format,
  44175. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  44176. } );
  44177. const srcView = textureGPU.createView( {
  44178. baseMipLevel: 0,
  44179. mipLevelCount: 1,
  44180. dimension: GPUTextureViewDimension.TwoD,
  44181. baseArrayLayer
  44182. } );
  44183. const dstView = tempTexture.createView( {
  44184. baseMipLevel: 0,
  44185. mipLevelCount: 1,
  44186. dimension: GPUTextureViewDimension.TwoD,
  44187. baseArrayLayer: 0
  44188. } );
  44189. const commandEncoder = this.device.createCommandEncoder( {} );
  44190. const pass = ( pipeline, sourceView, destinationView ) => {
  44191. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  44192. const bindGroup = this.device.createBindGroup( {
  44193. layout: bindGroupLayout,
  44194. entries: [ {
  44195. binding: 0,
  44196. resource: this.flipYSampler
  44197. }, {
  44198. binding: 1,
  44199. resource: sourceView
  44200. } ]
  44201. } );
  44202. const passEncoder = commandEncoder.beginRenderPass( {
  44203. colorAttachments: [ {
  44204. view: destinationView,
  44205. loadOp: GPULoadOp.Clear,
  44206. storeOp: GPUStoreOp.Store,
  44207. clearValue: [ 0, 0, 0, 0 ]
  44208. } ]
  44209. } );
  44210. passEncoder.setPipeline( pipeline );
  44211. passEncoder.setBindGroup( 0, bindGroup );
  44212. passEncoder.draw( 4, 1, 0, 0 );
  44213. passEncoder.end();
  44214. };
  44215. pass( transferPipeline, srcView, dstView );
  44216. pass( flipYPipeline, dstView, srcView );
  44217. this.device.queue.submit( [ commandEncoder.finish() ] );
  44218. tempTexture.destroy();
  44219. }
  44220. /**
  44221. * Generates mipmaps for the given GPU texture.
  44222. *
  44223. * @param {GPUTexture} textureGPU - The GPU texture object.
  44224. * @param {Object} textureGPUDescriptor - The texture descriptor.
  44225. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  44226. */
  44227. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  44228. const textureData = this.get( textureGPU );
  44229. if ( textureData.useCount === undefined ) {
  44230. textureData.useCount = 0;
  44231. textureData.layers = [];
  44232. }
  44233. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  44234. const commandEncoder = this.device.createCommandEncoder( {} );
  44235. this._mipmapRunBundles( commandEncoder, passes );
  44236. this.device.queue.submit( [ commandEncoder.finish() ] );
  44237. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  44238. textureData.useCount ++;
  44239. }
  44240. /**
  44241. * Since multiple copy render passes are required to generate mipmaps, the passes
  44242. * are managed as render bundles to improve performance.
  44243. *
  44244. * @param {GPUTexture} textureGPU - The GPU texture object.
  44245. * @param {Object} textureGPUDescriptor - The texture descriptor.
  44246. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  44247. * @return {Array<Object>} An array of render bundles.
  44248. */
  44249. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  44250. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  44251. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  44252. let srcView = textureGPU.createView( {
  44253. baseMipLevel: 0,
  44254. mipLevelCount: 1,
  44255. dimension: GPUTextureViewDimension.TwoD,
  44256. baseArrayLayer
  44257. } );
  44258. const passes = [];
  44259. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  44260. const bindGroup = this.device.createBindGroup( {
  44261. layout: bindGroupLayout,
  44262. entries: [ {
  44263. binding: 0,
  44264. resource: this.mipmapSampler
  44265. }, {
  44266. binding: 1,
  44267. resource: srcView
  44268. } ]
  44269. } );
  44270. const dstView = textureGPU.createView( {
  44271. baseMipLevel: i,
  44272. mipLevelCount: 1,
  44273. dimension: GPUTextureViewDimension.TwoD,
  44274. baseArrayLayer
  44275. } );
  44276. const passDescriptor = {
  44277. colorAttachments: [ {
  44278. view: dstView,
  44279. loadOp: GPULoadOp.Clear,
  44280. storeOp: GPUStoreOp.Store,
  44281. clearValue: [ 0, 0, 0, 0 ]
  44282. } ]
  44283. };
  44284. const passEncoder = this.device.createRenderBundleEncoder( {
  44285. colorFormats: [ textureGPUDescriptor.format ]
  44286. } );
  44287. passEncoder.setPipeline( pipeline );
  44288. passEncoder.setBindGroup( 0, bindGroup );
  44289. passEncoder.draw( 4, 1, 0, 0 );
  44290. passes.push( {
  44291. renderBundles: [ passEncoder.finish() ],
  44292. passDescriptor
  44293. } );
  44294. srcView = dstView;
  44295. }
  44296. return passes;
  44297. }
  44298. /**
  44299. * Executes the render bundles.
  44300. *
  44301. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  44302. * @param {Array<Object>} passes - An array of render bundles.
  44303. */
  44304. _mipmapRunBundles( commandEncoder, passes ) {
  44305. const levels = passes.length;
  44306. for ( let i = 0; i < levels; i ++ ) {
  44307. const pass = passes[ i ];
  44308. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  44309. passEncoder.executeBundles( pass.renderBundles );
  44310. passEncoder.end();
  44311. }
  44312. }
  44313. }
  44314. const _compareToWebGPU = {
  44315. [ NeverCompare ]: 'never',
  44316. [ LessCompare ]: 'less',
  44317. [ EqualCompare ]: 'equal',
  44318. [ LessEqualCompare ]: 'less-equal',
  44319. [ GreaterCompare ]: 'greater',
  44320. [ GreaterEqualCompare ]: 'greater-equal',
  44321. [ AlwaysCompare ]: 'always',
  44322. [ NotEqualCompare ]: 'not-equal'
  44323. };
  44324. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  44325. /**
  44326. * A WebGPU backend utility module for managing textures.
  44327. *
  44328. * @private
  44329. */
  44330. class WebGPUTextureUtils {
  44331. /**
  44332. * Constructs a new utility object.
  44333. *
  44334. * @param {WebGPUBackend} backend - The WebGPU backend.
  44335. */
  44336. constructor( backend ) {
  44337. /**
  44338. * A reference to the WebGPU backend.
  44339. *
  44340. * @type {WebGPUBackend}
  44341. */
  44342. this.backend = backend;
  44343. /**
  44344. * A reference to the pass utils.
  44345. *
  44346. * @type {?WebGPUTexturePassUtils}
  44347. * @default null
  44348. */
  44349. this._passUtils = null;
  44350. /**
  44351. * A dictionary for managing default textures. The key
  44352. * is the texture format, the value the texture object.
  44353. *
  44354. * @type {Object<string,Texture>}
  44355. */
  44356. this.defaultTexture = {};
  44357. /**
  44358. * A dictionary for managing default cube textures. The key
  44359. * is the texture format, the value the texture object.
  44360. *
  44361. * @type {Object<string,CubeTexture>}
  44362. */
  44363. this.defaultCubeTexture = {};
  44364. /**
  44365. * A default video frame.
  44366. *
  44367. * @type {?VideoFrame}
  44368. * @default null
  44369. */
  44370. this.defaultVideoFrame = null;
  44371. /**
  44372. * Represents the color attachment of the default framebuffer.
  44373. *
  44374. * @type {?GPUTexture}
  44375. * @default null
  44376. */
  44377. this.colorBuffer = null;
  44378. /**
  44379. * Represents the depth attachment of the default framebuffer.
  44380. *
  44381. * @type {DepthTexture}
  44382. */
  44383. this.depthTexture = new DepthTexture();
  44384. this.depthTexture.name = 'depthBuffer';
  44385. }
  44386. /**
  44387. * Creates a GPU sampler for the given texture.
  44388. *
  44389. * @param {Texture} texture - The texture to create the sampler for.
  44390. */
  44391. createSampler( texture ) {
  44392. const backend = this.backend;
  44393. const device = backend.device;
  44394. const textureGPU = backend.get( texture );
  44395. const samplerDescriptorGPU = {
  44396. addressModeU: this._convertAddressMode( texture.wrapS ),
  44397. addressModeV: this._convertAddressMode( texture.wrapT ),
  44398. addressModeW: this._convertAddressMode( texture.wrapR ),
  44399. magFilter: this._convertFilterMode( texture.magFilter ),
  44400. minFilter: this._convertFilterMode( texture.minFilter ),
  44401. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  44402. maxAnisotropy: 1
  44403. };
  44404. // anisotropy can only be used when all filter modes are set to linear.
  44405. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  44406. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  44407. }
  44408. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  44409. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  44410. }
  44411. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  44412. }
  44413. /**
  44414. * Creates a default texture for the given texture that can be used
  44415. * as a placeholder until the actual texture is ready for usage.
  44416. *
  44417. * @param {Texture} texture - The texture to create a default texture for.
  44418. */
  44419. createDefaultTexture( texture ) {
  44420. let textureGPU;
  44421. const format = getFormat( texture );
  44422. if ( texture.isCubeTexture ) {
  44423. textureGPU = this._getDefaultCubeTextureGPU( format );
  44424. } else if ( texture.isVideoTexture ) {
  44425. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  44426. } else {
  44427. textureGPU = this._getDefaultTextureGPU( format );
  44428. }
  44429. this.backend.get( texture ).texture = textureGPU;
  44430. }
  44431. /**
  44432. * Defines a texture on the GPU for the given texture object.
  44433. *
  44434. * @param {Texture} texture - The texture.
  44435. * @param {Object} [options={}] - Optional configuration parameter.
  44436. */
  44437. createTexture( texture, options = {} ) {
  44438. const backend = this.backend;
  44439. const textureData = backend.get( texture );
  44440. if ( textureData.initialized ) {
  44441. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  44442. }
  44443. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  44444. if ( options.levels === undefined ) options.levels = 1;
  44445. if ( options.depth === undefined ) options.depth = 1;
  44446. const { width, height, depth, levels } = options;
  44447. if ( texture.isFramebufferTexture ) {
  44448. if ( options.renderTarget ) {
  44449. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  44450. } else {
  44451. options.format = this.backend.utils.getPreferredCanvasFormat();
  44452. }
  44453. }
  44454. const dimension = this._getDimension( texture );
  44455. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  44456. textureData.format = format;
  44457. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  44458. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  44459. if ( texture.isStorageTexture === true ) {
  44460. usage |= GPUTextureUsage.STORAGE_BINDING;
  44461. }
  44462. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  44463. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  44464. }
  44465. const textureDescriptorGPU = {
  44466. label: texture.name,
  44467. size: {
  44468. width: width,
  44469. height: height,
  44470. depthOrArrayLayers: depth,
  44471. },
  44472. mipLevelCount: levels,
  44473. sampleCount: primarySamples,
  44474. dimension: dimension,
  44475. format: format,
  44476. usage: usage
  44477. };
  44478. // texture creation
  44479. if ( texture.isVideoTexture ) {
  44480. const video = texture.source.data;
  44481. const videoFrame = new VideoFrame( video );
  44482. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  44483. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  44484. videoFrame.close();
  44485. textureData.externalTexture = video;
  44486. } else {
  44487. if ( format === undefined ) {
  44488. console.warn( 'WebGPURenderer: Texture format not supported.' );
  44489. this.createDefaultTexture( texture );
  44490. return;
  44491. }
  44492. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  44493. }
  44494. if ( isMSAA ) {
  44495. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  44496. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  44497. msaaTextureDescriptorGPU.sampleCount = samples;
  44498. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  44499. }
  44500. textureData.initialized = true;
  44501. textureData.textureDescriptorGPU = textureDescriptorGPU;
  44502. }
  44503. /**
  44504. * Destroys the GPU data for the given texture object.
  44505. *
  44506. * @param {Texture} texture - The texture.
  44507. */
  44508. destroyTexture( texture ) {
  44509. const backend = this.backend;
  44510. const textureData = backend.get( texture );
  44511. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  44512. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  44513. backend.delete( texture );
  44514. }
  44515. /**
  44516. * Destroys the GPU sampler for the given texture.
  44517. *
  44518. * @param {Texture} texture - The texture to destroy the sampler for.
  44519. */
  44520. destroySampler( texture ) {
  44521. const backend = this.backend;
  44522. const textureData = backend.get( texture );
  44523. delete textureData.sampler;
  44524. }
  44525. /**
  44526. * Generates mipmaps for the given texture.
  44527. *
  44528. * @param {Texture} texture - The texture.
  44529. */
  44530. generateMipmaps( texture ) {
  44531. const textureData = this.backend.get( texture );
  44532. if ( texture.isCubeTexture ) {
  44533. for ( let i = 0; i < 6; i ++ ) {
  44534. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  44535. }
  44536. } else {
  44537. const depth = texture.image.depth || 1;
  44538. for ( let i = 0; i < depth; i ++ ) {
  44539. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  44540. }
  44541. }
  44542. }
  44543. /**
  44544. * Returns the color buffer representing the color
  44545. * attachment of the default framebuffer.
  44546. *
  44547. * @return {GPUTexture} The color buffer.
  44548. */
  44549. getColorBuffer() {
  44550. if ( this.colorBuffer ) this.colorBuffer.destroy();
  44551. const backend = this.backend;
  44552. const { width, height } = backend.getDrawingBufferSize();
  44553. this.colorBuffer = backend.device.createTexture( {
  44554. label: 'colorBuffer',
  44555. size: {
  44556. width: width,
  44557. height: height,
  44558. depthOrArrayLayers: 1
  44559. },
  44560. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  44561. format: backend.utils.getPreferredCanvasFormat(),
  44562. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  44563. } );
  44564. return this.colorBuffer;
  44565. }
  44566. /**
  44567. * Returns the depth buffer representing the depth
  44568. * attachment of the default framebuffer.
  44569. *
  44570. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  44571. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  44572. * @return {GPUTexture} The depth buffer.
  44573. */
  44574. getDepthBuffer( depth = true, stencil = false ) {
  44575. const backend = this.backend;
  44576. const { width, height } = backend.getDrawingBufferSize();
  44577. const depthTexture = this.depthTexture;
  44578. const depthTextureGPU = backend.get( depthTexture ).texture;
  44579. let format, type;
  44580. if ( stencil ) {
  44581. format = DepthStencilFormat;
  44582. type = UnsignedInt248Type;
  44583. } else if ( depth ) {
  44584. format = DepthFormat;
  44585. type = UnsignedIntType;
  44586. }
  44587. if ( depthTextureGPU !== undefined ) {
  44588. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  44589. return depthTextureGPU;
  44590. }
  44591. this.destroyTexture( depthTexture );
  44592. }
  44593. depthTexture.name = 'depthBuffer';
  44594. depthTexture.format = format;
  44595. depthTexture.type = type;
  44596. depthTexture.image.width = width;
  44597. depthTexture.image.height = height;
  44598. this.createTexture( depthTexture, { width, height } );
  44599. return backend.get( depthTexture ).texture;
  44600. }
  44601. /**
  44602. * Uploads the updated texture data to the GPU.
  44603. *
  44604. * @param {Texture} texture - The texture.
  44605. * @param {Object} [options={}] - Optional configuration parameter.
  44606. */
  44607. updateTexture( texture, options ) {
  44608. const textureData = this.backend.get( texture );
  44609. const { textureDescriptorGPU } = textureData;
  44610. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  44611. return;
  44612. // transfer texture data
  44613. if ( texture.isDataTexture ) {
  44614. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  44615. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  44616. for ( let i = 0; i < options.image.depth; i ++ ) {
  44617. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  44618. }
  44619. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  44620. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  44621. } else if ( texture.isCubeTexture ) {
  44622. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  44623. } else if ( texture.isVideoTexture ) {
  44624. const video = texture.source.data;
  44625. textureData.externalTexture = video;
  44626. } else {
  44627. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  44628. }
  44629. //
  44630. textureData.version = texture.version;
  44631. if ( texture.onUpdate ) texture.onUpdate( texture );
  44632. }
  44633. /**
  44634. * Returns texture data as a typed array.
  44635. *
  44636. * @async
  44637. * @param {Texture} texture - The texture to copy.
  44638. * @param {number} x - The x coordinate of the copy origin.
  44639. * @param {number} y - The y coordinate of the copy origin.
  44640. * @param {number} width - The width of the copy.
  44641. * @param {number} height - The height of the copy.
  44642. * @param {number} faceIndex - The face index.
  44643. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44644. */
  44645. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44646. const device = this.backend.device;
  44647. const textureData = this.backend.get( texture );
  44648. const textureGPU = textureData.texture;
  44649. const format = textureData.textureDescriptorGPU.format;
  44650. const bytesPerTexel = this._getBytesPerTexel( format );
  44651. let bytesPerRow = width * bytesPerTexel;
  44652. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  44653. const readBuffer = device.createBuffer(
  44654. {
  44655. size: width * height * bytesPerTexel,
  44656. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44657. }
  44658. );
  44659. const encoder = device.createCommandEncoder();
  44660. encoder.copyTextureToBuffer(
  44661. {
  44662. texture: textureGPU,
  44663. origin: { x, y, z: faceIndex },
  44664. },
  44665. {
  44666. buffer: readBuffer,
  44667. bytesPerRow: bytesPerRow
  44668. },
  44669. {
  44670. width: width,
  44671. height: height
  44672. }
  44673. );
  44674. const typedArrayType = this._getTypedArrayType( format );
  44675. device.queue.submit( [ encoder.finish() ] );
  44676. await readBuffer.mapAsync( GPUMapMode.READ );
  44677. const buffer = readBuffer.getMappedRange();
  44678. return new typedArrayType( buffer );
  44679. }
  44680. /**
  44681. * Returns `true` if the given texture is an environment map.
  44682. *
  44683. * @private
  44684. * @param {Texture} texture - The texture.
  44685. * @return {boolean} Whether the given texture is an environment map or not.
  44686. */
  44687. _isEnvironmentTexture( texture ) {
  44688. const mapping = texture.mapping;
  44689. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  44690. }
  44691. /**
  44692. * Returns the default GPU texture for the given format.
  44693. *
  44694. * @private
  44695. * @param {string} format - The GPU format.
  44696. * @return {GPUTexture} The GPU texture.
  44697. */
  44698. _getDefaultTextureGPU( format ) {
  44699. let defaultTexture = this.defaultTexture[ format ];
  44700. if ( defaultTexture === undefined ) {
  44701. const texture = new Texture();
  44702. texture.minFilter = NearestFilter;
  44703. texture.magFilter = NearestFilter;
  44704. this.createTexture( texture, { width: 1, height: 1, format } );
  44705. this.defaultTexture[ format ] = defaultTexture = texture;
  44706. }
  44707. return this.backend.get( defaultTexture ).texture;
  44708. }
  44709. /**
  44710. * Returns the default GPU cube texture for the given format.
  44711. *
  44712. * @private
  44713. * @param {string} format - The GPU format.
  44714. * @return {GPUTexture} The GPU texture.
  44715. */
  44716. _getDefaultCubeTextureGPU( format ) {
  44717. let defaultCubeTexture = this.defaultTexture[ format ];
  44718. if ( defaultCubeTexture === undefined ) {
  44719. const texture = new CubeTexture();
  44720. texture.minFilter = NearestFilter;
  44721. texture.magFilter = NearestFilter;
  44722. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  44723. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  44724. }
  44725. return this.backend.get( defaultCubeTexture ).texture;
  44726. }
  44727. /**
  44728. * Returns the default video frame used as default data in context of video textures.
  44729. *
  44730. * @private
  44731. * @return {VideoFrame} The video frame.
  44732. */
  44733. _getDefaultVideoFrame() {
  44734. let defaultVideoFrame = this.defaultVideoFrame;
  44735. if ( defaultVideoFrame === null ) {
  44736. const init = {
  44737. timestamp: 0,
  44738. codedWidth: 1,
  44739. codedHeight: 1,
  44740. format: 'RGBA',
  44741. };
  44742. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  44743. }
  44744. return defaultVideoFrame;
  44745. }
  44746. /**
  44747. * Uploads cube texture image data to the GPU memory.
  44748. *
  44749. * @private
  44750. * @param {Array} images - The cube image data.
  44751. * @param {GPUTexture} textureGPU - The GPU texture.
  44752. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44753. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44754. */
  44755. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  44756. for ( let i = 0; i < 6; i ++ ) {
  44757. const image = images[ i ];
  44758. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  44759. if ( image.isDataTexture ) {
  44760. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  44761. } else {
  44762. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  44763. }
  44764. }
  44765. }
  44766. /**
  44767. * Uploads texture image data to the GPU memory.
  44768. *
  44769. * @private
  44770. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  44771. * @param {GPUTexture} textureGPU - The GPU texture.
  44772. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44773. * @param {number} originDepth - The origin depth.
  44774. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44775. */
  44776. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  44777. const device = this.backend.device;
  44778. device.queue.copyExternalImageToTexture(
  44779. {
  44780. source: image,
  44781. flipY: flipY
  44782. }, {
  44783. texture: textureGPU,
  44784. mipLevel: 0,
  44785. origin: { x: 0, y: 0, z: originDepth }
  44786. }, {
  44787. width: image.width,
  44788. height: image.height,
  44789. depthOrArrayLayers: 1
  44790. }
  44791. );
  44792. }
  44793. /**
  44794. * Returns the pass utils singleton.
  44795. *
  44796. * @private
  44797. * @return {WebGPUTexturePassUtils} The utils instance.
  44798. */
  44799. _getPassUtils() {
  44800. let passUtils = this._passUtils;
  44801. if ( passUtils === null ) {
  44802. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  44803. }
  44804. return passUtils;
  44805. }
  44806. /**
  44807. * Generates mipmaps for the given GPU texture.
  44808. *
  44809. * @private
  44810. * @param {GPUTexture} textureGPU - The GPU texture object.
  44811. * @param {Object} textureDescriptorGPU - The texture descriptor.
  44812. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  44813. */
  44814. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  44815. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  44816. }
  44817. /**
  44818. * Flip the contents of the given GPU texture along its vertical axis.
  44819. *
  44820. * @private
  44821. * @param {GPUTexture} textureGPU - The GPU texture object.
  44822. * @param {Object} textureDescriptorGPU - The texture descriptor.
  44823. * @param {number} [originDepth=0] - The origin depth.
  44824. */
  44825. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  44826. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  44827. }
  44828. /**
  44829. * Uploads texture buffer data to the GPU memory.
  44830. *
  44831. * @private
  44832. * @param {Object} image - An object defining the image buffer data.
  44833. * @param {GPUTexture} textureGPU - The GPU texture.
  44834. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44835. * @param {number} originDepth - The origin depth.
  44836. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  44837. * @param {number} [depth=0] - TODO.
  44838. */
  44839. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  44840. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  44841. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  44842. const device = this.backend.device;
  44843. const data = image.data;
  44844. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  44845. const bytesPerRow = image.width * bytesPerTexel;
  44846. device.queue.writeTexture(
  44847. {
  44848. texture: textureGPU,
  44849. mipLevel: 0,
  44850. origin: { x: 0, y: 0, z: originDepth }
  44851. },
  44852. data,
  44853. {
  44854. offset: image.width * image.height * bytesPerTexel * depth,
  44855. bytesPerRow
  44856. },
  44857. {
  44858. width: image.width,
  44859. height: image.height,
  44860. depthOrArrayLayers: 1
  44861. } );
  44862. if ( flipY === true ) {
  44863. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  44864. }
  44865. }
  44866. /**
  44867. * Uploads compressed texture data to the GPU memory.
  44868. *
  44869. * @private
  44870. * @param {Array<Object>} mipmaps - An array with mipmap data.
  44871. * @param {GPUTexture} textureGPU - The GPU texture.
  44872. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  44873. */
  44874. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  44875. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  44876. const device = this.backend.device;
  44877. const blockData = this._getBlockData( textureDescriptorGPU.format );
  44878. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  44879. for ( let i = 0; i < mipmaps.length; i ++ ) {
  44880. const mipmap = mipmaps[ i ];
  44881. const width = mipmap.width;
  44882. const height = mipmap.height;
  44883. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  44884. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  44885. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  44886. for ( let j = 0; j < depth; j ++ ) {
  44887. device.queue.writeTexture(
  44888. {
  44889. texture: textureGPU,
  44890. mipLevel: i,
  44891. origin: { x: 0, y: 0, z: j }
  44892. },
  44893. mipmap.data,
  44894. {
  44895. offset: j * bytesPerImage,
  44896. bytesPerRow,
  44897. rowsPerImage: Math.ceil( height / blockData.height )
  44898. },
  44899. {
  44900. width: Math.ceil( width / blockData.width ) * blockData.width,
  44901. height: Math.ceil( height / blockData.height ) * blockData.height,
  44902. depthOrArrayLayers: 1
  44903. }
  44904. );
  44905. }
  44906. }
  44907. }
  44908. /**
  44909. * This method is only relevant for compressed texture formats. It returns a block
  44910. * data descriptor for the given GPU compressed texture format.
  44911. *
  44912. * @private
  44913. * @param {string} format - The GPU compressed texture format.
  44914. * @return {Object} The block data descriptor.
  44915. */
  44916. _getBlockData( format ) {
  44917. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  44918. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  44919. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  44920. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  44921. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  44922. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  44923. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  44924. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  44925. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  44926. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  44927. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  44928. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  44929. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  44930. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  44931. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  44932. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  44933. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  44934. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  44935. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  44936. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  44937. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  44938. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  44939. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  44940. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  44941. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  44942. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  44943. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  44944. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  44945. }
  44946. /**
  44947. * Converts the three.js uv wrapping constants to GPU address mode constants.
  44948. *
  44949. * @private
  44950. * @param {number} value - The three.js constant defining a uv wrapping mode.
  44951. * @return {string} The GPU address mode.
  44952. */
  44953. _convertAddressMode( value ) {
  44954. let addressMode = GPUAddressMode.ClampToEdge;
  44955. if ( value === RepeatWrapping ) {
  44956. addressMode = GPUAddressMode.Repeat;
  44957. } else if ( value === MirroredRepeatWrapping ) {
  44958. addressMode = GPUAddressMode.MirrorRepeat;
  44959. }
  44960. return addressMode;
  44961. }
  44962. /**
  44963. * Converts the three.js filter constants to GPU filter constants.
  44964. *
  44965. * @private
  44966. * @param {number} value - The three.js constant defining a filter mode.
  44967. * @return {string} The GPU filter mode.
  44968. */
  44969. _convertFilterMode( value ) {
  44970. let filterMode = GPUFilterMode.Linear;
  44971. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  44972. filterMode = GPUFilterMode.Nearest;
  44973. }
  44974. return filterMode;
  44975. }
  44976. /**
  44977. * Returns the bytes-per-texel value for the given GPU texture format.
  44978. *
  44979. * @private
  44980. * @param {string} format - The GPU texture format.
  44981. * @return {number} The bytes-per-texel.
  44982. */
  44983. _getBytesPerTexel( format ) {
  44984. // 8-bit formats
  44985. if ( format === GPUTextureFormat.R8Unorm ||
  44986. format === GPUTextureFormat.R8Snorm ||
  44987. format === GPUTextureFormat.R8Uint ||
  44988. format === GPUTextureFormat.R8Sint ) return 1;
  44989. // 16-bit formats
  44990. if ( format === GPUTextureFormat.R16Uint ||
  44991. format === GPUTextureFormat.R16Sint ||
  44992. format === GPUTextureFormat.R16Float ||
  44993. format === GPUTextureFormat.RG8Unorm ||
  44994. format === GPUTextureFormat.RG8Snorm ||
  44995. format === GPUTextureFormat.RG8Uint ||
  44996. format === GPUTextureFormat.RG8Sint ) return 2;
  44997. // 32-bit formats
  44998. if ( format === GPUTextureFormat.R32Uint ||
  44999. format === GPUTextureFormat.R32Sint ||
  45000. format === GPUTextureFormat.R32Float ||
  45001. format === GPUTextureFormat.RG16Uint ||
  45002. format === GPUTextureFormat.RG16Sint ||
  45003. format === GPUTextureFormat.RG16Float ||
  45004. format === GPUTextureFormat.RGBA8Unorm ||
  45005. format === GPUTextureFormat.RGBA8UnormSRGB ||
  45006. format === GPUTextureFormat.RGBA8Snorm ||
  45007. format === GPUTextureFormat.RGBA8Uint ||
  45008. format === GPUTextureFormat.RGBA8Sint ||
  45009. format === GPUTextureFormat.BGRA8Unorm ||
  45010. format === GPUTextureFormat.BGRA8UnormSRGB ||
  45011. // Packed 32-bit formats
  45012. format === GPUTextureFormat.RGB9E5UFloat ||
  45013. format === GPUTextureFormat.RGB10A2Unorm ||
  45014. format === GPUTextureFormat.RG11B10UFloat ||
  45015. format === GPUTextureFormat.Depth32Float ||
  45016. format === GPUTextureFormat.Depth24Plus ||
  45017. format === GPUTextureFormat.Depth24PlusStencil8 ||
  45018. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  45019. // 64-bit formats
  45020. if ( format === GPUTextureFormat.RG32Uint ||
  45021. format === GPUTextureFormat.RG32Sint ||
  45022. format === GPUTextureFormat.RG32Float ||
  45023. format === GPUTextureFormat.RGBA16Uint ||
  45024. format === GPUTextureFormat.RGBA16Sint ||
  45025. format === GPUTextureFormat.RGBA16Float ) return 8;
  45026. // 128-bit formats
  45027. if ( format === GPUTextureFormat.RGBA32Uint ||
  45028. format === GPUTextureFormat.RGBA32Sint ||
  45029. format === GPUTextureFormat.RGBA32Float ) return 16;
  45030. }
  45031. /**
  45032. * Returns the corresponding typed array type for the given GPU texture format.
  45033. *
  45034. * @private
  45035. * @param {string} format - The GPU texture format.
  45036. * @return {TypedArray.constructor} The typed array type.
  45037. */
  45038. _getTypedArrayType( format ) {
  45039. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  45040. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  45041. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  45042. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  45043. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  45044. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  45045. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  45046. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  45047. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  45048. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  45049. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  45050. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  45051. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  45052. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  45053. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  45054. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  45055. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  45056. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  45057. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  45058. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  45059. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  45060. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  45061. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  45062. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  45063. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  45064. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  45065. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  45066. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  45067. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  45068. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  45069. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  45070. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  45071. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  45072. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  45073. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  45074. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  45075. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  45076. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  45077. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  45078. }
  45079. /**
  45080. * Returns the GPU dimensions for the given texture.
  45081. *
  45082. * @private
  45083. * @param {Texture} texture - The texture.
  45084. * @return {string} The GPU dimension.
  45085. */
  45086. _getDimension( texture ) {
  45087. let dimension;
  45088. if ( texture.isData3DTexture ) {
  45089. dimension = GPUTextureDimension.ThreeD;
  45090. } else {
  45091. dimension = GPUTextureDimension.TwoD;
  45092. }
  45093. return dimension;
  45094. }
  45095. }
  45096. /**
  45097. * Returns the GPU format for the given texture.
  45098. *
  45099. * @param {Texture} texture - The texture.
  45100. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  45101. * It is not necessary to apply the device for most formats.
  45102. * @return {string} The GPU format.
  45103. */
  45104. function getFormat( texture, device = null ) {
  45105. const format = texture.format;
  45106. const type = texture.type;
  45107. const colorSpace = texture.colorSpace;
  45108. let formatGPU;
  45109. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  45110. switch ( format ) {
  45111. case RGBA_S3TC_DXT1_Format:
  45112. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  45113. break;
  45114. case RGBA_S3TC_DXT3_Format:
  45115. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  45116. break;
  45117. case RGBA_S3TC_DXT5_Format:
  45118. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  45119. break;
  45120. case RGB_ETC2_Format:
  45121. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  45122. break;
  45123. case RGBA_ETC2_EAC_Format:
  45124. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  45125. break;
  45126. case RGBA_ASTC_4x4_Format:
  45127. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  45128. break;
  45129. case RGBA_ASTC_5x4_Format:
  45130. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  45131. break;
  45132. case RGBA_ASTC_5x5_Format:
  45133. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  45134. break;
  45135. case RGBA_ASTC_6x5_Format:
  45136. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  45137. break;
  45138. case RGBA_ASTC_6x6_Format:
  45139. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  45140. break;
  45141. case RGBA_ASTC_8x5_Format:
  45142. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  45143. break;
  45144. case RGBA_ASTC_8x6_Format:
  45145. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  45146. break;
  45147. case RGBA_ASTC_8x8_Format:
  45148. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  45149. break;
  45150. case RGBA_ASTC_10x5_Format:
  45151. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  45152. break;
  45153. case RGBA_ASTC_10x6_Format:
  45154. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  45155. break;
  45156. case RGBA_ASTC_10x8_Format:
  45157. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  45158. break;
  45159. case RGBA_ASTC_10x10_Format:
  45160. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  45161. break;
  45162. case RGBA_ASTC_12x10_Format:
  45163. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  45164. break;
  45165. case RGBA_ASTC_12x12_Format:
  45166. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  45167. break;
  45168. case RGBAFormat:
  45169. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  45170. break;
  45171. default:
  45172. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  45173. }
  45174. } else {
  45175. switch ( format ) {
  45176. case RGBAFormat:
  45177. switch ( type ) {
  45178. case ByteType:
  45179. formatGPU = GPUTextureFormat.RGBA8Snorm;
  45180. break;
  45181. case ShortType:
  45182. formatGPU = GPUTextureFormat.RGBA16Sint;
  45183. break;
  45184. case UnsignedShortType:
  45185. formatGPU = GPUTextureFormat.RGBA16Uint;
  45186. break;
  45187. case UnsignedIntType:
  45188. formatGPU = GPUTextureFormat.RGBA32Uint;
  45189. break;
  45190. case IntType:
  45191. formatGPU = GPUTextureFormat.RGBA32Sint;
  45192. break;
  45193. case UnsignedByteType:
  45194. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  45195. break;
  45196. case HalfFloatType:
  45197. formatGPU = GPUTextureFormat.RGBA16Float;
  45198. break;
  45199. case FloatType:
  45200. formatGPU = GPUTextureFormat.RGBA32Float;
  45201. break;
  45202. default:
  45203. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  45204. }
  45205. break;
  45206. case RGBFormat:
  45207. switch ( type ) {
  45208. case UnsignedInt5999Type:
  45209. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  45210. break;
  45211. default:
  45212. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  45213. }
  45214. break;
  45215. case RedFormat:
  45216. switch ( type ) {
  45217. case ByteType:
  45218. formatGPU = GPUTextureFormat.R8Snorm;
  45219. break;
  45220. case ShortType:
  45221. formatGPU = GPUTextureFormat.R16Sint;
  45222. break;
  45223. case UnsignedShortType:
  45224. formatGPU = GPUTextureFormat.R16Uint;
  45225. break;
  45226. case UnsignedIntType:
  45227. formatGPU = GPUTextureFormat.R32Uint;
  45228. break;
  45229. case IntType:
  45230. formatGPU = GPUTextureFormat.R32Sint;
  45231. break;
  45232. case UnsignedByteType:
  45233. formatGPU = GPUTextureFormat.R8Unorm;
  45234. break;
  45235. case HalfFloatType:
  45236. formatGPU = GPUTextureFormat.R16Float;
  45237. break;
  45238. case FloatType:
  45239. formatGPU = GPUTextureFormat.R32Float;
  45240. break;
  45241. default:
  45242. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  45243. }
  45244. break;
  45245. case RGFormat:
  45246. switch ( type ) {
  45247. case ByteType:
  45248. formatGPU = GPUTextureFormat.RG8Snorm;
  45249. break;
  45250. case ShortType:
  45251. formatGPU = GPUTextureFormat.RG16Sint;
  45252. break;
  45253. case UnsignedShortType:
  45254. formatGPU = GPUTextureFormat.RG16Uint;
  45255. break;
  45256. case UnsignedIntType:
  45257. formatGPU = GPUTextureFormat.RG32Uint;
  45258. break;
  45259. case IntType:
  45260. formatGPU = GPUTextureFormat.RG32Sint;
  45261. break;
  45262. case UnsignedByteType:
  45263. formatGPU = GPUTextureFormat.RG8Unorm;
  45264. break;
  45265. case HalfFloatType:
  45266. formatGPU = GPUTextureFormat.RG16Float;
  45267. break;
  45268. case FloatType:
  45269. formatGPU = GPUTextureFormat.RG32Float;
  45270. break;
  45271. default:
  45272. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  45273. }
  45274. break;
  45275. case DepthFormat:
  45276. switch ( type ) {
  45277. case UnsignedShortType:
  45278. formatGPU = GPUTextureFormat.Depth16Unorm;
  45279. break;
  45280. case UnsignedIntType:
  45281. formatGPU = GPUTextureFormat.Depth24Plus;
  45282. break;
  45283. case FloatType:
  45284. formatGPU = GPUTextureFormat.Depth32Float;
  45285. break;
  45286. default:
  45287. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  45288. }
  45289. break;
  45290. case DepthStencilFormat:
  45291. switch ( type ) {
  45292. case UnsignedInt248Type:
  45293. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  45294. break;
  45295. case FloatType:
  45296. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  45297. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  45298. }
  45299. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  45300. break;
  45301. default:
  45302. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  45303. }
  45304. break;
  45305. case RedIntegerFormat:
  45306. switch ( type ) {
  45307. case IntType:
  45308. formatGPU = GPUTextureFormat.R32Sint;
  45309. break;
  45310. case UnsignedIntType:
  45311. formatGPU = GPUTextureFormat.R32Uint;
  45312. break;
  45313. default:
  45314. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  45315. }
  45316. break;
  45317. case RGIntegerFormat:
  45318. switch ( type ) {
  45319. case IntType:
  45320. formatGPU = GPUTextureFormat.RG32Sint;
  45321. break;
  45322. case UnsignedIntType:
  45323. formatGPU = GPUTextureFormat.RG32Uint;
  45324. break;
  45325. default:
  45326. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  45327. }
  45328. break;
  45329. case RGBAIntegerFormat:
  45330. switch ( type ) {
  45331. case IntType:
  45332. formatGPU = GPUTextureFormat.RGBA32Sint;
  45333. break;
  45334. case UnsignedIntType:
  45335. formatGPU = GPUTextureFormat.RGBA32Uint;
  45336. break;
  45337. default:
  45338. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  45339. }
  45340. break;
  45341. default:
  45342. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  45343. }
  45344. }
  45345. return formatGPU;
  45346. }
  45347. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  45348. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  45349. const wgslTypeLib$1 = {
  45350. 'f32': 'float',
  45351. 'i32': 'int',
  45352. 'u32': 'uint',
  45353. 'bool': 'bool',
  45354. 'vec2<f32>': 'vec2',
  45355. 'vec2<i32>': 'ivec2',
  45356. 'vec2<u32>': 'uvec2',
  45357. 'vec2<bool>': 'bvec2',
  45358. 'vec2f': 'vec2',
  45359. 'vec2i': 'ivec2',
  45360. 'vec2u': 'uvec2',
  45361. 'vec2b': 'bvec2',
  45362. 'vec3<f32>': 'vec3',
  45363. 'vec3<i32>': 'ivec3',
  45364. 'vec3<u32>': 'uvec3',
  45365. 'vec3<bool>': 'bvec3',
  45366. 'vec3f': 'vec3',
  45367. 'vec3i': 'ivec3',
  45368. 'vec3u': 'uvec3',
  45369. 'vec3b': 'bvec3',
  45370. 'vec4<f32>': 'vec4',
  45371. 'vec4<i32>': 'ivec4',
  45372. 'vec4<u32>': 'uvec4',
  45373. 'vec4<bool>': 'bvec4',
  45374. 'vec4f': 'vec4',
  45375. 'vec4i': 'ivec4',
  45376. 'vec4u': 'uvec4',
  45377. 'vec4b': 'bvec4',
  45378. 'mat2x2<f32>': 'mat2',
  45379. 'mat2x2f': 'mat2',
  45380. 'mat3x3<f32>': 'mat3',
  45381. 'mat3x3f': 'mat3',
  45382. 'mat4x4<f32>': 'mat4',
  45383. 'mat4x4f': 'mat4',
  45384. 'sampler': 'sampler',
  45385. 'texture_1d': 'texture',
  45386. 'texture_2d': 'texture',
  45387. 'texture_2d_array': 'texture',
  45388. 'texture_multisampled_2d': 'cubeTexture',
  45389. 'texture_depth_2d': 'depthTexture',
  45390. 'texture_depth_multisampled_2d': 'depthTexture',
  45391. 'texture_3d': 'texture3D',
  45392. 'texture_cube': 'cubeTexture',
  45393. 'texture_cube_array': 'cubeTexture',
  45394. 'texture_storage_1d': 'storageTexture',
  45395. 'texture_storage_2d': 'storageTexture',
  45396. 'texture_storage_2d_array': 'storageTexture',
  45397. 'texture_storage_3d': 'storageTexture'
  45398. };
  45399. const parse = ( source ) => {
  45400. source = source.trim();
  45401. const declaration = source.match( declarationRegexp );
  45402. if ( declaration !== null && declaration.length === 4 ) {
  45403. const inputsCode = declaration[ 2 ];
  45404. const propsMatches = [];
  45405. let match = null;
  45406. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  45407. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  45408. }
  45409. // Process matches to correctly pair names and types
  45410. const inputs = [];
  45411. for ( let i = 0; i < propsMatches.length; i ++ ) {
  45412. const { name, type } = propsMatches[ i ];
  45413. let resolvedType = type;
  45414. if ( resolvedType.startsWith( 'ptr' ) ) {
  45415. resolvedType = 'pointer';
  45416. } else {
  45417. if ( resolvedType.startsWith( 'texture' ) ) {
  45418. resolvedType = type.split( '<' )[ 0 ];
  45419. }
  45420. resolvedType = wgslTypeLib$1[ resolvedType ];
  45421. }
  45422. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  45423. }
  45424. const blockCode = source.substring( declaration[ 0 ].length );
  45425. const outputType = declaration[ 3 ] || 'void';
  45426. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  45427. const type = wgslTypeLib$1[ outputType ] || outputType;
  45428. return {
  45429. type,
  45430. inputs,
  45431. name,
  45432. inputsCode,
  45433. blockCode,
  45434. outputType
  45435. };
  45436. } else {
  45437. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  45438. }
  45439. };
  45440. /**
  45441. * This class represents a WSL node function.
  45442. *
  45443. * @augments NodeFunction
  45444. */
  45445. class WGSLNodeFunction extends NodeFunction {
  45446. /**
  45447. * Constructs a new WGSL node function.
  45448. *
  45449. * @param {string} source - The WGSL source.
  45450. */
  45451. constructor( source ) {
  45452. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  45453. super( type, inputs, name );
  45454. this.inputsCode = inputsCode;
  45455. this.blockCode = blockCode;
  45456. this.outputType = outputType;
  45457. }
  45458. /**
  45459. * This method returns the WGSL code of the node function.
  45460. *
  45461. * @param {string} [name=this.name] - The function's name.
  45462. * @return {string} The shader code.
  45463. */
  45464. getCode( name = this.name ) {
  45465. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  45466. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  45467. }
  45468. }
  45469. /**
  45470. * A WGSL node parser.
  45471. *
  45472. * @augments NodeParser
  45473. */
  45474. class WGSLNodeParser extends NodeParser {
  45475. /**
  45476. * The method parses the given WGSL code an returns a node function.
  45477. *
  45478. * @param {string} source - The WGSL code.
  45479. * @return {WGSLNodeFunction} A node function.
  45480. */
  45481. parseFunction( source ) {
  45482. return new WGSLNodeFunction( source );
  45483. }
  45484. }
  45485. // GPUShaderStage is not defined in browsers not supporting WebGPU
  45486. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  45487. const accessNames = {
  45488. [ NodeAccess.READ_ONLY ]: 'read',
  45489. [ NodeAccess.WRITE_ONLY ]: 'write',
  45490. [ NodeAccess.READ_WRITE ]: 'read_write'
  45491. };
  45492. const wrapNames = {
  45493. [ RepeatWrapping ]: 'repeat',
  45494. [ ClampToEdgeWrapping ]: 'clamp',
  45495. [ MirroredRepeatWrapping ]: 'mirror'
  45496. };
  45497. const gpuShaderStageLib = {
  45498. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  45499. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  45500. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  45501. };
  45502. const supports = {
  45503. instance: true,
  45504. swizzleAssign: false,
  45505. storageBuffer: true
  45506. };
  45507. const wgslFnOpLib = {
  45508. '^^': 'tsl_xor'
  45509. };
  45510. const wgslTypeLib = {
  45511. float: 'f32',
  45512. int: 'i32',
  45513. uint: 'u32',
  45514. bool: 'bool',
  45515. color: 'vec3<f32>',
  45516. vec2: 'vec2<f32>',
  45517. ivec2: 'vec2<i32>',
  45518. uvec2: 'vec2<u32>',
  45519. bvec2: 'vec2<bool>',
  45520. vec3: 'vec3<f32>',
  45521. ivec3: 'vec3<i32>',
  45522. uvec3: 'vec3<u32>',
  45523. bvec3: 'vec3<bool>',
  45524. vec4: 'vec4<f32>',
  45525. ivec4: 'vec4<i32>',
  45526. uvec4: 'vec4<u32>',
  45527. bvec4: 'vec4<bool>',
  45528. mat2: 'mat2x2<f32>',
  45529. mat3: 'mat3x3<f32>',
  45530. mat4: 'mat4x4<f32>'
  45531. };
  45532. const wgslCodeCache = {};
  45533. const wgslPolyfill = {
  45534. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  45535. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  45536. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  45537. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  45538. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  45539. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  45540. 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 ); }' ),
  45541. 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 ); }' ),
  45542. 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 ); }' ),
  45543. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  45544. 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 ); }' ),
  45545. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  45546. biquadraticTexture: new CodeNode( /* wgsl */`
  45547. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  45548. let res = vec2f( iRes );
  45549. let uvScaled = coord * res;
  45550. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  45551. // https://www.shadertoy.com/view/WtyXRy
  45552. let uv = uvWrapping - 0.5;
  45553. let iuv = floor( uv );
  45554. let f = fract( uv );
  45555. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  45556. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  45557. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  45558. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  45559. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  45560. }
  45561. ` )
  45562. };
  45563. const wgslMethods = {
  45564. dFdx: 'dpdx',
  45565. dFdy: '- dpdy',
  45566. mod_float: 'tsl_mod_float',
  45567. mod_vec2: 'tsl_mod_vec2',
  45568. mod_vec3: 'tsl_mod_vec3',
  45569. mod_vec4: 'tsl_mod_vec4',
  45570. equals_bool: 'tsl_equals_bool',
  45571. equals_bvec2: 'tsl_equals_bvec2',
  45572. equals_bvec3: 'tsl_equals_bvec3',
  45573. equals_bvec4: 'tsl_equals_bvec4',
  45574. inversesqrt: 'inverseSqrt',
  45575. bitcast: 'bitcast<f32>'
  45576. };
  45577. // WebGPU issue: does not support pow() with negative base on Windows
  45578. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  45579. 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 ); }' );
  45580. 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 ] );
  45581. 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 ] );
  45582. 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 ] );
  45583. wgslMethods.pow_float = 'tsl_pow_float';
  45584. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  45585. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  45586. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  45587. }
  45588. //
  45589. let diagnostics = '';
  45590. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  45591. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  45592. }
  45593. /**
  45594. * A node builder targeting WGSL.
  45595. *
  45596. * This module generates WGSL shader code from node materials and also
  45597. * generates the respective bindings and vertex buffer definitions. These
  45598. * data are later used by the renderer to create render and compute pipelines
  45599. * for render objects.
  45600. *
  45601. * @augments NodeBuilder
  45602. */
  45603. class WGSLNodeBuilder extends NodeBuilder {
  45604. /**
  45605. * Constructs a new WGSL node builder renderer.
  45606. *
  45607. * @param {Object3D} object - The 3D object.
  45608. * @param {Renderer} renderer - The renderer.
  45609. */
  45610. constructor( object, renderer ) {
  45611. super( object, renderer, new WGSLNodeParser() );
  45612. /**
  45613. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  45614. * another dictionary which manages UBOs per group ('render','frame','object').
  45615. *
  45616. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  45617. */
  45618. this.uniformGroups = {};
  45619. /**
  45620. * A dictionary that holds for each shader stage a Map of builtins.
  45621. *
  45622. * @type {Object<string,Map<string,Object>>}
  45623. */
  45624. this.builtins = {};
  45625. /**
  45626. * A dictionary that holds for each shader stage a Set of directives.
  45627. *
  45628. * @type {Object<string,Set<string>>}
  45629. */
  45630. this.directives = {};
  45631. /**
  45632. * A map for managing scope arrays. Only relevant for when using
  45633. * {@link WorkgroupInfoNode} in context of compute shaders.
  45634. *
  45635. * @type {Map<string,Object>}
  45636. */
  45637. this.scopedArrays = new Map();
  45638. }
  45639. /**
  45640. * Checks if the given texture requires a manual conversion to the working color space.
  45641. *
  45642. * @param {Texture} texture - The texture to check.
  45643. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  45644. */
  45645. needsToWorkingColorSpace( texture ) {
  45646. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  45647. }
  45648. /**
  45649. * Generates the WGSL snippet for sampled textures.
  45650. *
  45651. * @private
  45652. * @param {Texture} texture - The texture.
  45653. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45654. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45655. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45656. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45657. * @return {string} The WGSL snippet.
  45658. */
  45659. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45660. if ( shaderStage === 'fragment' ) {
  45661. if ( depthSnippet ) {
  45662. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  45663. } else {
  45664. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  45665. }
  45666. } else if ( this.isFilteredTexture( texture ) ) {
  45667. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  45668. } else {
  45669. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  45670. }
  45671. }
  45672. /**
  45673. * Generates the WGSL snippet when sampling video textures.
  45674. *
  45675. * @private
  45676. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  45677. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45678. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45679. * @return {string} The WGSL snippet.
  45680. */
  45681. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  45682. if ( shaderStage === 'fragment' ) {
  45683. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  45684. } else {
  45685. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  45686. }
  45687. }
  45688. /**
  45689. * Generates the WGSL snippet when sampling textures with explicit mip level.
  45690. *
  45691. * @private
  45692. * @param {Texture} texture - The texture.
  45693. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45694. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45695. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45696. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45697. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45698. * @return {string} The WGSL snippet.
  45699. */
  45700. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45701. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  45702. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  45703. } else if ( this.isFilteredTexture( texture ) ) {
  45704. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  45705. } else {
  45706. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  45707. }
  45708. }
  45709. /**
  45710. * Generates a wrap function used in context of textures.
  45711. *
  45712. * @param {Texture} texture - The texture to generate the function for.
  45713. * @return {string} The name of the generated function.
  45714. */
  45715. generateWrapFunction( texture ) {
  45716. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  45717. let nodeCode = wgslCodeCache[ functionName ];
  45718. if ( nodeCode === undefined ) {
  45719. const includes = [];
  45720. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  45721. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  45722. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  45723. const addWrapSnippet = ( wrap, axis ) => {
  45724. if ( wrap === RepeatWrapping ) {
  45725. includes.push( wgslPolyfill.repeatWrapping_float );
  45726. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  45727. } else if ( wrap === ClampToEdgeWrapping ) {
  45728. includes.push( wgslPolyfill.clampWrapping_float );
  45729. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  45730. } else if ( wrap === MirroredRepeatWrapping ) {
  45731. includes.push( wgslPolyfill.mirrorWrapping_float );
  45732. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  45733. } else {
  45734. code += `\t\tcoord.${ axis }`;
  45735. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  45736. }
  45737. };
  45738. addWrapSnippet( texture.wrapS, 'x' );
  45739. code += ',\n';
  45740. addWrapSnippet( texture.wrapT, 'y' );
  45741. if ( texture.isData3DTexture ) {
  45742. code += ',\n';
  45743. addWrapSnippet( texture.wrapR, 'z' );
  45744. }
  45745. code += '\n\t);\n\n}\n';
  45746. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  45747. }
  45748. nodeCode.build( this );
  45749. return functionName;
  45750. }
  45751. /**
  45752. * Generates the array declaration string.
  45753. *
  45754. * @param {string} type - The type.
  45755. * @param {?number} [count] - The count.
  45756. * @return {string} The generated value as a shader string.
  45757. */
  45758. generateArrayDeclaration( type, count ) {
  45759. return `array< ${ this.getType( type ) }, ${ count } >`;
  45760. }
  45761. /**
  45762. * Generates a WGSL variable that holds the texture dimension of the given texture.
  45763. * It also returns information about the the number of layers (elements) of an arrayed
  45764. * texture as well as the cube face count of cube textures.
  45765. *
  45766. * @param {Texture} texture - The texture to generate the function for.
  45767. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  45768. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45769. * @return {string} The name of the dimension variable.
  45770. */
  45771. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  45772. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  45773. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  45774. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  45775. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  45776. let textureDimensionsParams;
  45777. let dimensionType;
  45778. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  45779. const isMultisampled = primarySamples > 1;
  45780. if ( texture.isData3DTexture ) {
  45781. dimensionType = 'vec3<u32>';
  45782. } else {
  45783. // Regular 2D textures, depth textures, etc.
  45784. dimensionType = 'vec2<u32>';
  45785. }
  45786. // Build parameters string based on texture type and multisampling
  45787. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  45788. textureDimensionsParams = textureProperty;
  45789. } else {
  45790. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  45791. }
  45792. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  45793. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  45794. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  45795. textureData.arrayLayerCount = new VarNode(
  45796. new ExpressionNode(
  45797. `textureNumLayers(${textureProperty})`,
  45798. 'u32'
  45799. )
  45800. );
  45801. }
  45802. // For cube textures, we know it's always 6 faces
  45803. if ( texture.isTextureCube ) {
  45804. textureData.cubeFaceCount = new VarNode(
  45805. new ExpressionNode( '6u', 'u32' )
  45806. );
  45807. }
  45808. }
  45809. return textureDimensionNode.build( this );
  45810. }
  45811. /**
  45812. * Generates the WGSL snippet for a manual filtered texture.
  45813. *
  45814. * @param {Texture} texture - The texture.
  45815. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45816. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45817. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45818. * @return {string} The WGSL snippet.
  45819. */
  45820. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  45821. this._include( 'biquadraticTexture' );
  45822. const wrapFunction = this.generateWrapFunction( texture );
  45823. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  45824. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  45825. }
  45826. /**
  45827. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  45828. * Since it's a lookup, no sampling or filtering is applied.
  45829. *
  45830. * @param {Texture} texture - The texture.
  45831. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45832. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45833. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45834. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45835. * @return {string} The WGSL snippet.
  45836. */
  45837. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  45838. const wrapFunction = this.generateWrapFunction( texture );
  45839. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  45840. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  45841. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  45842. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  45843. }
  45844. /**
  45845. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  45846. *
  45847. * @param {Texture} texture - The texture.
  45848. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45849. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45850. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45851. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45852. * @return {string} The WGSL snippet.
  45853. */
  45854. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  45855. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  45856. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  45857. } else if ( depthSnippet ) {
  45858. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  45859. } else {
  45860. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  45861. }
  45862. }
  45863. /**
  45864. * Generates the WGSL snippet that writes a single texel to a texture.
  45865. *
  45866. * @param {Texture} texture - The texture.
  45867. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45868. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45869. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  45870. * @return {string} The WGSL snippet.
  45871. */
  45872. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  45873. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  45874. }
  45875. /**
  45876. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  45877. *
  45878. * @param {Texture} texture - The texture.
  45879. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  45880. */
  45881. isSampleCompare( texture ) {
  45882. return texture.isDepthTexture === true && texture.compareFunction !== null;
  45883. }
  45884. /**
  45885. * Returns `true` if the given texture is unfilterable.
  45886. *
  45887. * @param {Texture} texture - The texture.
  45888. * @return {boolean} Whether the given texture is unfilterable or not.
  45889. */
  45890. isUnfilterable( texture ) {
  45891. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  45892. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  45893. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  45894. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  45895. }
  45896. /**
  45897. * Generates the WGSL snippet for sampling/loading the given texture.
  45898. *
  45899. * @param {Texture} texture - The texture.
  45900. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45901. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45902. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45903. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45904. * @return {string} The WGSL snippet.
  45905. */
  45906. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45907. let snippet = null;
  45908. if ( texture.isVideoTexture === true ) {
  45909. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  45910. } else if ( this.isUnfilterable( texture ) ) {
  45911. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  45912. } else {
  45913. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  45914. }
  45915. return snippet;
  45916. }
  45917. /**
  45918. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  45919. *
  45920. * @param {Texture} texture - The texture.
  45921. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45922. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45923. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  45924. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45925. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45926. * @return {string} The WGSL snippet.
  45927. */
  45928. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45929. if ( shaderStage === 'fragment' ) {
  45930. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  45931. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  45932. } else {
  45933. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  45934. }
  45935. }
  45936. /**
  45937. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  45938. * against a reference value.
  45939. *
  45940. * @param {Texture} texture - The texture.
  45941. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45942. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45943. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  45944. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45945. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45946. * @return {string} The WGSL snippet.
  45947. */
  45948. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45949. if ( shaderStage === 'fragment' ) {
  45950. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  45951. } else {
  45952. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  45953. }
  45954. }
  45955. /**
  45956. * Generates the WGSL snippet when sampling textures with explicit mip level.
  45957. *
  45958. * @param {Texture} texture - The texture.
  45959. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45960. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45961. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  45962. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45963. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45964. * @return {string} The WGSL snippet.
  45965. */
  45966. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45967. let snippet = null;
  45968. if ( texture.isVideoTexture === true ) {
  45969. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  45970. } else {
  45971. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  45972. }
  45973. return snippet;
  45974. }
  45975. /**
  45976. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  45977. *
  45978. * @param {Texture} texture - The texture.
  45979. * @param {string} textureProperty - The name of the texture uniform in the shader.
  45980. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  45981. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  45982. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  45983. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45984. * @return {string} The WGSL snippet.
  45985. */
  45986. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  45987. if ( shaderStage === 'fragment' ) {
  45988. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  45989. } else {
  45990. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  45991. }
  45992. }
  45993. /**
  45994. * Returns a WGSL snippet that represents the property name of the given node.
  45995. *
  45996. * @param {Node} node - The node.
  45997. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  45998. * @return {string} The property name.
  45999. */
  46000. getPropertyName( node, shaderStage = this.shaderStage ) {
  46001. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  46002. if ( shaderStage === 'vertex' ) {
  46003. return `varyings.${ node.name }`;
  46004. }
  46005. } else if ( node.isNodeUniform === true ) {
  46006. const name = node.name;
  46007. const type = node.type;
  46008. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  46009. return name;
  46010. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  46011. if ( this.isCustomStruct( node ) ) {
  46012. return name;
  46013. }
  46014. return name + '.value';
  46015. } else {
  46016. return node.groupNode.name + '.' + name;
  46017. }
  46018. }
  46019. return super.getPropertyName( node );
  46020. }
  46021. /**
  46022. * Returns the output struct name.
  46023. *
  46024. * @return {string} The name of the output struct.
  46025. */
  46026. getOutputStructName() {
  46027. return 'output';
  46028. }
  46029. /**
  46030. * Returns the native shader operator name for a given generic name.
  46031. *
  46032. * @param {string} op - The operator name to resolve.
  46033. * @return {?string} The resolved operator name.
  46034. */
  46035. getFunctionOperator( op ) {
  46036. const fnOp = wgslFnOpLib[ op ];
  46037. if ( fnOp !== undefined ) {
  46038. this._include( fnOp );
  46039. return fnOp;
  46040. }
  46041. return null;
  46042. }
  46043. /**
  46044. * Returns the node access for the given node and shader stage.
  46045. *
  46046. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  46047. * @param {string} shaderStage - The shader stage.
  46048. * @return {string} The node access.
  46049. */
  46050. getNodeAccess( node, shaderStage ) {
  46051. if ( shaderStage !== 'compute' )
  46052. return NodeAccess.READ_ONLY;
  46053. return node.access;
  46054. }
  46055. /**
  46056. * Returns A WGSL snippet representing the storage access.
  46057. *
  46058. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  46059. * @param {string} shaderStage - The shader stage.
  46060. * @return {string} The WGSL snippet representing the storage access.
  46061. */
  46062. getStorageAccess( node, shaderStage ) {
  46063. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  46064. }
  46065. /**
  46066. * This method is one of the more important ones since it's responsible
  46067. * for generating a matching binding instance for the given uniform node.
  46068. *
  46069. * These bindings are later used in the renderer to create bind groups
  46070. * and layouts.
  46071. *
  46072. * @param {UniformNode} node - The uniform node.
  46073. * @param {string} type - The node data type.
  46074. * @param {string} shaderStage - The shader stage.
  46075. * @param {?string} [name=null] - An optional uniform name.
  46076. * @return {NodeUniform} The node uniform object.
  46077. */
  46078. getUniformFromNode( node, type, shaderStage, name = null ) {
  46079. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  46080. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  46081. if ( nodeData.uniformGPU === undefined ) {
  46082. let uniformGPU;
  46083. const group = node.groupNode;
  46084. const groupName = group.name;
  46085. const bindings = this.getBindGroupArray( groupName, shaderStage );
  46086. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  46087. let texture = null;
  46088. const access = this.getNodeAccess( node, shaderStage );
  46089. if ( type === 'texture' || type === 'storageTexture' ) {
  46090. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  46091. } else if ( type === 'cubeTexture' ) {
  46092. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  46093. } else if ( type === 'texture3D' ) {
  46094. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  46095. }
  46096. texture.store = node.isStorageTextureNode === true;
  46097. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  46098. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  46099. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  46100. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  46101. bindings.push( sampler, texture );
  46102. uniformGPU = [ sampler, texture ];
  46103. } else {
  46104. bindings.push( texture );
  46105. uniformGPU = [ texture ];
  46106. }
  46107. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  46108. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  46109. const buffer = new bufferClass( node, group );
  46110. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  46111. bindings.push( buffer );
  46112. uniformGPU = buffer;
  46113. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  46114. } else {
  46115. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  46116. let uniformsGroup = uniformsStage[ groupName ];
  46117. if ( uniformsGroup === undefined ) {
  46118. uniformsGroup = new NodeUniformsGroup( groupName, group );
  46119. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  46120. uniformsStage[ groupName ] = uniformsGroup;
  46121. bindings.push( uniformsGroup );
  46122. }
  46123. uniformGPU = this.getNodeUniform( uniformNode, type );
  46124. uniformsGroup.addUniform( uniformGPU );
  46125. }
  46126. nodeData.uniformGPU = uniformGPU;
  46127. }
  46128. return uniformNode;
  46129. }
  46130. /**
  46131. * This method should be used whenever builtins are required in nodes.
  46132. * The internal builtins data structure will make sure builtins are
  46133. * defined in the WGSL source.
  46134. *
  46135. * @param {string} name - The builtin name.
  46136. * @param {string} property - The property name.
  46137. * @param {string} type - The node data type.
  46138. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46139. * @return {string} The property name.
  46140. */
  46141. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  46142. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  46143. if ( map.has( name ) === false ) {
  46144. map.set( name, {
  46145. name,
  46146. property,
  46147. type
  46148. } );
  46149. }
  46150. return property;
  46151. }
  46152. /**
  46153. * Returns `true` if the given builtin is defined in the given shader stage.
  46154. *
  46155. * @param {string} name - The builtin name.
  46156. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46157. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  46158. */
  46159. hasBuiltin( name, shaderStage = this.shaderStage ) {
  46160. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  46161. }
  46162. /**
  46163. * Returns the vertex index builtin.
  46164. *
  46165. * @return {string} The vertex index.
  46166. */
  46167. getVertexIndex() {
  46168. if ( this.shaderStage === 'vertex' ) {
  46169. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  46170. }
  46171. return 'vertexIndex';
  46172. }
  46173. /**
  46174. * Builds the given shader node.
  46175. *
  46176. * @param {ShaderNodeInternal} shaderNode - The shader node.
  46177. * @return {string} The WGSL function code.
  46178. */
  46179. buildFunctionCode( shaderNode ) {
  46180. const layout = shaderNode.layout;
  46181. const flowData = this.flowShaderNode( shaderNode );
  46182. const parameters = [];
  46183. for ( const input of layout.inputs ) {
  46184. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  46185. }
  46186. //
  46187. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  46188. ${ flowData.vars }
  46189. ${ flowData.code }
  46190. `;
  46191. if ( flowData.result ) {
  46192. code += `\treturn ${ flowData.result };\n`;
  46193. }
  46194. code += '\n}\n';
  46195. //
  46196. return code;
  46197. }
  46198. /**
  46199. * Returns the instance index builtin.
  46200. *
  46201. * @return {string} The instance index.
  46202. */
  46203. getInstanceIndex() {
  46204. if ( this.shaderStage === 'vertex' ) {
  46205. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  46206. }
  46207. return 'instanceIndex';
  46208. }
  46209. /**
  46210. * Returns the invocation local index builtin.
  46211. *
  46212. * @return {string} The invocation local index.
  46213. */
  46214. getInvocationLocalIndex() {
  46215. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  46216. }
  46217. /**
  46218. * Returns the subgroup size builtin.
  46219. *
  46220. * @return {string} The subgroup size.
  46221. */
  46222. getSubgroupSize() {
  46223. this.enableSubGroups();
  46224. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  46225. }
  46226. /**
  46227. * Returns the invocation subgroup index builtin.
  46228. *
  46229. * @return {string} The invocation subgroup index.
  46230. */
  46231. getInvocationSubgroupIndex() {
  46232. this.enableSubGroups();
  46233. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  46234. }
  46235. /**
  46236. * Returns the subgroup index builtin.
  46237. *
  46238. * @return {string} The subgroup index.
  46239. */
  46240. getSubgroupIndex() {
  46241. this.enableSubGroups();
  46242. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  46243. }
  46244. /**
  46245. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  46246. *
  46247. * @return {null} Null.
  46248. */
  46249. getDrawIndex() {
  46250. return null;
  46251. }
  46252. /**
  46253. * Returns the front facing builtin.
  46254. *
  46255. * @return {string} The front facing builtin.
  46256. */
  46257. getFrontFacing() {
  46258. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  46259. }
  46260. /**
  46261. * Returns the frag coord builtin.
  46262. *
  46263. * @return {string} The frag coord builtin.
  46264. */
  46265. getFragCoord() {
  46266. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  46267. }
  46268. /**
  46269. * Returns the frag depth builtin.
  46270. *
  46271. * @return {string} The frag depth builtin.
  46272. */
  46273. getFragDepth() {
  46274. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  46275. }
  46276. /**
  46277. * Returns the clip distances builtin.
  46278. *
  46279. * @return {string} The clip distances builtin.
  46280. */
  46281. getClipDistance() {
  46282. return 'varyings.hw_clip_distances';
  46283. }
  46284. /**
  46285. * Whether to flip texture data along its vertical axis or not.
  46286. *
  46287. * @return {boolean} Returns always `false` in context of WGSL.
  46288. */
  46289. isFlipY() {
  46290. return false;
  46291. }
  46292. /**
  46293. * Enables the given directive for the given shader stage.
  46294. *
  46295. * @param {string} name - The directive name.
  46296. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  46297. */
  46298. enableDirective( name, shaderStage = this.shaderStage ) {
  46299. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  46300. stage.add( name );
  46301. }
  46302. /**
  46303. * Returns the directives of the given shader stage as a WGSL string.
  46304. *
  46305. * @param {string} shaderStage - The shader stage.
  46306. * @return {string} A WGSL snippet that enables the directives of the given stage.
  46307. */
  46308. getDirectives( shaderStage ) {
  46309. const snippets = [];
  46310. const directives = this.directives[ shaderStage ];
  46311. if ( directives !== undefined ) {
  46312. for ( const directive of directives ) {
  46313. snippets.push( `enable ${directive};` );
  46314. }
  46315. }
  46316. return snippets.join( '\n' );
  46317. }
  46318. /**
  46319. * Enables the 'subgroups' directive.
  46320. */
  46321. enableSubGroups() {
  46322. this.enableDirective( 'subgroups' );
  46323. }
  46324. /**
  46325. * Enables the 'subgroups-f16' directive.
  46326. */
  46327. enableSubgroupsF16() {
  46328. this.enableDirective( 'subgroups-f16' );
  46329. }
  46330. /**
  46331. * Enables the 'clip_distances' directive.
  46332. */
  46333. enableClipDistances() {
  46334. this.enableDirective( 'clip_distances' );
  46335. }
  46336. /**
  46337. * Enables the 'f16' directive.
  46338. */
  46339. enableShaderF16() {
  46340. this.enableDirective( 'f16' );
  46341. }
  46342. /**
  46343. * Enables the 'dual_source_blending' directive.
  46344. */
  46345. enableDualSourceBlending() {
  46346. this.enableDirective( 'dual_source_blending' );
  46347. }
  46348. /**
  46349. * Enables hardware clipping.
  46350. *
  46351. * @param {string} planeCount - The clipping plane count.
  46352. */
  46353. enableHardwareClipping( planeCount ) {
  46354. this.enableClipDistances();
  46355. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  46356. }
  46357. /**
  46358. * Returns the builtins of the given shader stage as a WGSL string.
  46359. *
  46360. * @param {string} shaderStage - The shader stage.
  46361. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  46362. */
  46363. getBuiltins( shaderStage ) {
  46364. const snippets = [];
  46365. const builtins = this.builtins[ shaderStage ];
  46366. if ( builtins !== undefined ) {
  46367. for ( const { name, property, type } of builtins.values() ) {
  46368. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  46369. }
  46370. }
  46371. return snippets.join( ',\n\t' );
  46372. }
  46373. /**
  46374. * This method should be used when a new scoped buffer is used in context of
  46375. * compute shaders. It adds the array to the internal data structure which is
  46376. * later used to generate the respective WGSL.
  46377. *
  46378. * @param {string} name - The array name.
  46379. * @param {string} scope - The scope.
  46380. * @param {string} bufferType - The buffer type.
  46381. * @param {string} bufferCount - The buffer count.
  46382. * @return {string} The array name.
  46383. */
  46384. getScopedArray( name, scope, bufferType, bufferCount ) {
  46385. if ( this.scopedArrays.has( name ) === false ) {
  46386. this.scopedArrays.set( name, {
  46387. name,
  46388. scope,
  46389. bufferType,
  46390. bufferCount
  46391. } );
  46392. }
  46393. return name;
  46394. }
  46395. /**
  46396. * Returns the scoped arrays of the given shader stage as a WGSL string.
  46397. *
  46398. * @param {string} shaderStage - The shader stage.
  46399. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  46400. * Returns `undefined` when used in the vertex or fragment stage.
  46401. */
  46402. getScopedArrays( shaderStage ) {
  46403. if ( shaderStage !== 'compute' ) {
  46404. return;
  46405. }
  46406. const snippets = [];
  46407. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  46408. const type = this.getType( bufferType );
  46409. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  46410. }
  46411. return snippets.join( '\n' );
  46412. }
  46413. /**
  46414. * Returns the shader attributes of the given shader stage as a WGSL string.
  46415. *
  46416. * @param {string} shaderStage - The shader stage.
  46417. * @return {string} The WGSL snippet that defines the shader attributes.
  46418. */
  46419. getAttributes( shaderStage ) {
  46420. const snippets = [];
  46421. if ( shaderStage === 'compute' ) {
  46422. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  46423. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  46424. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  46425. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  46426. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  46427. this.enableDirective( 'subgroups', shaderStage );
  46428. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  46429. }
  46430. }
  46431. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  46432. const builtins = this.getBuiltins( 'attribute' );
  46433. if ( builtins ) snippets.push( builtins );
  46434. const attributes = this.getAttributesArray();
  46435. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  46436. const attribute = attributes[ index ];
  46437. const name = attribute.name;
  46438. const type = this.getType( attribute.type );
  46439. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  46440. }
  46441. }
  46442. return snippets.join( ',\n\t' );
  46443. }
  46444. /**
  46445. * Returns the members of the given struct type node as a WGSL string.
  46446. *
  46447. * @param {StructTypeNode} struct - The struct type node.
  46448. * @return {string} The WGSL snippet that defines the struct members.
  46449. */
  46450. getStructMembers( struct ) {
  46451. const snippets = [];
  46452. for ( const member of struct.members ) {
  46453. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  46454. let type = this.getType( member.type );
  46455. if ( member.atomic ) {
  46456. type = 'atomic< ' + type + ' >';
  46457. }
  46458. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  46459. }
  46460. if ( struct.output ) {
  46461. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  46462. }
  46463. return snippets.join( ',\n' );
  46464. }
  46465. /**
  46466. * Returns the structs of the given shader stage as a WGSL string.
  46467. *
  46468. * @param {string} shaderStage - The shader stage.
  46469. * @return {string} The WGSL snippet that defines the structs.
  46470. */
  46471. getStructs( shaderStage ) {
  46472. let result = '';
  46473. const structs = this.structs[ shaderStage ];
  46474. if ( structs.length > 0 ) {
  46475. const snippets = [];
  46476. for ( const struct of structs ) {
  46477. let snippet = `struct ${ struct.name } {\n`;
  46478. snippet += this.getStructMembers( struct );
  46479. snippet += '\n};';
  46480. snippets.push( snippet );
  46481. }
  46482. result = '\n' + snippets.join( '\n\n' ) + '\n';
  46483. }
  46484. return result;
  46485. }
  46486. /**
  46487. * Returns a WGSL string representing a variable.
  46488. *
  46489. * @param {string} type - The variable's type.
  46490. * @param {string} name - The variable's name.
  46491. * @param {?number} [count=null] - The array length.
  46492. * @return {string} The WGSL snippet that defines a variable.
  46493. */
  46494. getVar( type, name, count = null ) {
  46495. let snippet = `var ${ name } : `;
  46496. if ( count !== null ) {
  46497. snippet += this.generateArrayDeclaration( type, count );
  46498. } else {
  46499. snippet += this.getType( type );
  46500. }
  46501. return snippet;
  46502. }
  46503. /**
  46504. * Returns the variables of the given shader stage as a WGSL string.
  46505. *
  46506. * @param {string} shaderStage - The shader stage.
  46507. * @return {string} The WGSL snippet that defines the variables.
  46508. */
  46509. getVars( shaderStage ) {
  46510. const snippets = [];
  46511. const vars = this.vars[ shaderStage ];
  46512. if ( vars !== undefined ) {
  46513. for ( const variable of vars ) {
  46514. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  46515. }
  46516. }
  46517. return `\n${ snippets.join( '\n' ) }\n`;
  46518. }
  46519. /**
  46520. * Returns the varyings of the given shader stage as a WGSL string.
  46521. *
  46522. * @param {string} shaderStage - The shader stage.
  46523. * @return {string} The WGSL snippet that defines the varyings.
  46524. */
  46525. getVaryings( shaderStage ) {
  46526. const snippets = [];
  46527. if ( shaderStage === 'vertex' ) {
  46528. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  46529. }
  46530. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  46531. const varyings = this.varyings;
  46532. const vars = this.vars[ shaderStage ];
  46533. for ( let index = 0; index < varyings.length; index ++ ) {
  46534. const varying = varyings[ index ];
  46535. if ( varying.needsInterpolation ) {
  46536. let attributesSnippet = `@location( ${index} )`;
  46537. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  46538. attributesSnippet += ' @interpolate( flat )';
  46539. }
  46540. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  46541. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  46542. vars.push( varying );
  46543. }
  46544. }
  46545. }
  46546. const builtins = this.getBuiltins( shaderStage );
  46547. if ( builtins ) snippets.push( builtins );
  46548. const code = snippets.join( ',\n\t' );
  46549. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  46550. }
  46551. isCustomStruct( nodeUniform ) {
  46552. return nodeUniform.value.isStorageBufferAttribute && nodeUniform.node.structTypeNode !== null;
  46553. }
  46554. /**
  46555. * Returns the uniforms of the given shader stage as a WGSL string.
  46556. *
  46557. * @param {string} shaderStage - The shader stage.
  46558. * @return {string} The WGSL snippet that defines the uniforms.
  46559. */
  46560. getUniforms( shaderStage ) {
  46561. const uniforms = this.uniforms[ shaderStage ];
  46562. const bindingSnippets = [];
  46563. const bufferSnippets = [];
  46564. const structSnippets = [];
  46565. const uniformGroups = {};
  46566. for ( const uniform of uniforms ) {
  46567. const groupName = uniform.groupNode.name;
  46568. const uniformIndexes = this.bindingsIndexes[ groupName ];
  46569. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  46570. const texture = uniform.node.value;
  46571. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  46572. if ( this.isSampleCompare( texture ) ) {
  46573. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  46574. } else {
  46575. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  46576. }
  46577. }
  46578. let textureType;
  46579. let multisampled = '';
  46580. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  46581. if ( primarySamples > 1 ) {
  46582. multisampled = '_multisampled';
  46583. }
  46584. if ( texture.isCubeTexture === true ) {
  46585. textureType = 'texture_cube<f32>';
  46586. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  46587. textureType = 'texture_2d_array<f32>';
  46588. } else if ( texture.isDepthTexture === true ) {
  46589. textureType = `texture_depth${multisampled}_2d`;
  46590. } else if ( texture.isVideoTexture === true ) {
  46591. textureType = 'texture_external';
  46592. } else if ( texture.isData3DTexture === true ) {
  46593. textureType = 'texture_3d<f32>';
  46594. } else if ( uniform.node.isStorageTextureNode === true ) {
  46595. const format = getFormat( texture );
  46596. const access = this.getStorageAccess( uniform.node, shaderStage );
  46597. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  46598. } else {
  46599. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  46600. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  46601. }
  46602. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  46603. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  46604. const bufferNode = uniform.node;
  46605. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  46606. const bufferCount = bufferNode.bufferCount;
  46607. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  46608. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  46609. if ( this.isCustomStruct( uniform ) ) {
  46610. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  46611. } else {
  46612. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  46613. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  46614. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  46615. }
  46616. } else {
  46617. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  46618. const groupName = uniform.groupNode.name;
  46619. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  46620. index: uniformIndexes.binding ++,
  46621. id: uniformIndexes.group,
  46622. snippets: []
  46623. } );
  46624. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  46625. }
  46626. }
  46627. for ( const name in uniformGroups ) {
  46628. const group = uniformGroups[ name ];
  46629. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  46630. }
  46631. let code = bindingSnippets.join( '\n' );
  46632. code += bufferSnippets.join( '\n' );
  46633. code += structSnippets.join( '\n' );
  46634. return code;
  46635. }
  46636. /**
  46637. * Controls the code build of the shader stages.
  46638. */
  46639. buildCode() {
  46640. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  46641. this.sortBindingGroups();
  46642. for ( const shaderStage in shadersData ) {
  46643. this.shaderStage = shaderStage;
  46644. const stageData = shadersData[ shaderStage ];
  46645. stageData.uniforms = this.getUniforms( shaderStage );
  46646. stageData.attributes = this.getAttributes( shaderStage );
  46647. stageData.varyings = this.getVaryings( shaderStage );
  46648. stageData.structs = this.getStructs( shaderStage );
  46649. stageData.vars = this.getVars( shaderStage );
  46650. stageData.codes = this.getCodes( shaderStage );
  46651. stageData.directives = this.getDirectives( shaderStage );
  46652. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  46653. //
  46654. let flow = '// code\n\n';
  46655. flow += this.flowCode[ shaderStage ];
  46656. const flowNodes = this.flowNodes[ shaderStage ];
  46657. const mainNode = flowNodes[ flowNodes.length - 1 ];
  46658. const outputNode = mainNode.outputNode;
  46659. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  46660. for ( const node of flowNodes ) {
  46661. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  46662. const slotName = node.name;
  46663. if ( slotName ) {
  46664. if ( flow.length > 0 ) flow += '\n';
  46665. flow += `\t// flow -> ${ slotName }\n`;
  46666. }
  46667. flow += `${ flowSlotData.code }\n\t`;
  46668. if ( node === mainNode && shaderStage !== 'compute' ) {
  46669. flow += '// result\n\n\t';
  46670. if ( shaderStage === 'vertex' ) {
  46671. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  46672. } else if ( shaderStage === 'fragment' ) {
  46673. if ( isOutputStruct ) {
  46674. stageData.returnType = outputNode.getNodeType( this );
  46675. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  46676. flow += `return ${ flowSlotData.result };`;
  46677. } else {
  46678. let structSnippet = '\t@location(0) color: vec4<f32>';
  46679. const builtins = this.getBuiltins( 'output' );
  46680. if ( builtins ) structSnippet += ',\n\t' + builtins;
  46681. stageData.returnType = 'OutputStruct';
  46682. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  46683. stageData.structs += '\nvar<private> output : OutputStruct;';
  46684. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  46685. }
  46686. }
  46687. }
  46688. }
  46689. stageData.flow = flow;
  46690. }
  46691. this.shaderStage = null;
  46692. if ( this.material !== null ) {
  46693. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  46694. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  46695. } else {
  46696. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  46697. }
  46698. }
  46699. /**
  46700. * Returns the native shader method name for a given generic name.
  46701. *
  46702. * @param {string} method - The method name to resolve.
  46703. * @param {?string} [output=null] - An optional output.
  46704. * @return {string} The resolved WGSL method name.
  46705. */
  46706. getMethod( method, output = null ) {
  46707. let wgslMethod;
  46708. if ( output !== null ) {
  46709. wgslMethod = this._getWGSLMethod( method + '_' + output );
  46710. }
  46711. if ( wgslMethod === undefined ) {
  46712. wgslMethod = this._getWGSLMethod( method );
  46713. }
  46714. return wgslMethod || method;
  46715. }
  46716. /**
  46717. * Returns the WGSL type of the given node data type.
  46718. *
  46719. * @param {string} type - The node data type.
  46720. * @return {string} The WGSL type.
  46721. */
  46722. getType( type ) {
  46723. return wgslTypeLib[ type ] || type;
  46724. }
  46725. /**
  46726. * Whether the requested feature is available or not.
  46727. *
  46728. * @param {string} name - The requested feature.
  46729. * @return {boolean} Whether the requested feature is supported or not.
  46730. */
  46731. isAvailable( name ) {
  46732. let result = supports[ name ];
  46733. if ( result === undefined ) {
  46734. if ( name === 'float32Filterable' ) {
  46735. result = this.renderer.hasFeature( 'float32-filterable' );
  46736. } else if ( name === 'clipDistance' ) {
  46737. result = this.renderer.hasFeature( 'clip-distances' );
  46738. }
  46739. supports[ name ] = result;
  46740. }
  46741. return result;
  46742. }
  46743. /**
  46744. * Returns the native shader method name for a given generic name.
  46745. *
  46746. * @private
  46747. * @param {string} method - The method name to resolve.
  46748. * @return {string} The resolved WGSL method name.
  46749. */
  46750. _getWGSLMethod( method ) {
  46751. if ( wgslPolyfill[ method ] !== undefined ) {
  46752. this._include( method );
  46753. }
  46754. return wgslMethods[ method ];
  46755. }
  46756. /**
  46757. * Includes the given method name into the current
  46758. * function node.
  46759. *
  46760. * @private
  46761. * @param {string} name - The method name to include.
  46762. * @return {CodeNode} The respective code node.
  46763. */
  46764. _include( name ) {
  46765. const codeNode = wgslPolyfill[ name ];
  46766. codeNode.build( this );
  46767. if ( this.currentFunctionNode !== null ) {
  46768. this.currentFunctionNode.includes.push( codeNode );
  46769. }
  46770. return codeNode;
  46771. }
  46772. /**
  46773. * Returns a WGSL vertex shader based on the given shader data.
  46774. *
  46775. * @private
  46776. * @param {Object} shaderData - The shader data.
  46777. * @return {string} The vertex shader.
  46778. */
  46779. _getWGSLVertexCode( shaderData ) {
  46780. return `${ this.getSignature() }
  46781. // directives
  46782. ${shaderData.directives}
  46783. // structs
  46784. ${shaderData.structs}
  46785. // uniforms
  46786. ${shaderData.uniforms}
  46787. // varyings
  46788. ${shaderData.varyings}
  46789. var<private> varyings : VaryingsStruct;
  46790. // codes
  46791. ${shaderData.codes}
  46792. @vertex
  46793. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  46794. // vars
  46795. ${shaderData.vars}
  46796. // flow
  46797. ${shaderData.flow}
  46798. return varyings;
  46799. }
  46800. `;
  46801. }
  46802. /**
  46803. * Returns a WGSL fragment shader based on the given shader data.
  46804. *
  46805. * @private
  46806. * @param {Object} shaderData - The shader data.
  46807. * @return {string} The vertex shader.
  46808. */
  46809. _getWGSLFragmentCode( shaderData ) {
  46810. return `${ this.getSignature() }
  46811. // global
  46812. ${ diagnostics }
  46813. // structs
  46814. ${shaderData.structs}
  46815. // uniforms
  46816. ${shaderData.uniforms}
  46817. // codes
  46818. ${shaderData.codes}
  46819. @fragment
  46820. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  46821. // vars
  46822. ${shaderData.vars}
  46823. // flow
  46824. ${shaderData.flow}
  46825. }
  46826. `;
  46827. }
  46828. /**
  46829. * Returns a WGSL compute shader based on the given shader data.
  46830. *
  46831. * @private
  46832. * @param {Object} shaderData - The shader data.
  46833. * @param {string} workgroupSize - The workgroup size.
  46834. * @return {string} The vertex shader.
  46835. */
  46836. _getWGSLComputeCode( shaderData, workgroupSize ) {
  46837. return `${ this.getSignature() }
  46838. // directives
  46839. ${shaderData.directives}
  46840. // system
  46841. var<private> instanceIndex : u32;
  46842. // locals
  46843. ${shaderData.scopedArrays}
  46844. // structs
  46845. ${shaderData.structs}
  46846. // uniforms
  46847. ${shaderData.uniforms}
  46848. // codes
  46849. ${shaderData.codes}
  46850. @compute @workgroup_size( ${workgroupSize} )
  46851. fn main( ${shaderData.attributes} ) {
  46852. // system
  46853. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  46854. // vars
  46855. ${shaderData.vars}
  46856. // flow
  46857. ${shaderData.flow}
  46858. }
  46859. `;
  46860. }
  46861. /**
  46862. * Returns a WGSL struct based on the given name and variables.
  46863. *
  46864. * @private
  46865. * @param {string} name - The struct name.
  46866. * @param {string} vars - The struct variables.
  46867. * @return {string} The WGSL snippet representing a struct.
  46868. */
  46869. _getWGSLStruct( name, vars ) {
  46870. return `
  46871. struct ${name} {
  46872. ${vars}
  46873. };`;
  46874. }
  46875. /**
  46876. * Returns a WGSL struct binding.
  46877. *
  46878. * @private
  46879. * @param {string} name - The struct name.
  46880. * @param {string} vars - The struct variables.
  46881. * @param {string} access - The access.
  46882. * @param {number} [binding=0] - The binding index.
  46883. * @param {number} [group=0] - The group index.
  46884. * @return {string} The WGSL snippet representing a struct binding.
  46885. */
  46886. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  46887. const structName = name + 'Struct';
  46888. const structSnippet = this._getWGSLStruct( structName, vars );
  46889. return `${structSnippet}
  46890. @binding( ${ binding } ) @group( ${ group } )
  46891. var<${access}> ${ name } : ${ structName };`;
  46892. }
  46893. }
  46894. /**
  46895. * A WebGPU backend utility module with common helpers.
  46896. *
  46897. * @private
  46898. */
  46899. class WebGPUUtils {
  46900. /**
  46901. * Constructs a new utility object.
  46902. *
  46903. * @param {WebGPUBackend} backend - The WebGPU backend.
  46904. */
  46905. constructor( backend ) {
  46906. /**
  46907. * A reference to the WebGPU backend.
  46908. *
  46909. * @type {WebGPUBackend}
  46910. */
  46911. this.backend = backend;
  46912. }
  46913. /**
  46914. * Returns the depth/stencil GPU format for the given render context.
  46915. *
  46916. * @param {RenderContext} renderContext - The render context.
  46917. * @return {string} The depth/stencil GPU texture format.
  46918. */
  46919. getCurrentDepthStencilFormat( renderContext ) {
  46920. let format;
  46921. if ( renderContext.depthTexture !== null ) {
  46922. format = this.getTextureFormatGPU( renderContext.depthTexture );
  46923. } else if ( renderContext.depth && renderContext.stencil ) {
  46924. format = GPUTextureFormat.Depth24PlusStencil8;
  46925. } else if ( renderContext.depth ) {
  46926. format = GPUTextureFormat.Depth24Plus;
  46927. }
  46928. return format;
  46929. }
  46930. /**
  46931. * Returns the GPU format for the given texture.
  46932. *
  46933. * @param {Texture} texture - The texture.
  46934. * @return {string} The GPU texture format.
  46935. */
  46936. getTextureFormatGPU( texture ) {
  46937. return this.backend.get( texture ).format;
  46938. }
  46939. /**
  46940. * Returns an object that defines the multi-sampling state of the given texture.
  46941. *
  46942. * @param {Texture} texture - The texture.
  46943. * @return {Object} The multi-sampling state.
  46944. */
  46945. getTextureSampleData( texture ) {
  46946. let samples;
  46947. if ( texture.isFramebufferTexture ) {
  46948. samples = 1;
  46949. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  46950. const renderer = this.backend.renderer;
  46951. const renderTarget = renderer.getRenderTarget();
  46952. samples = renderTarget ? renderTarget.samples : renderer.samples;
  46953. } else if ( texture.renderTarget ) {
  46954. samples = texture.renderTarget.samples;
  46955. }
  46956. samples = samples || 1;
  46957. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  46958. const primarySamples = isMSAA ? 1 : samples;
  46959. return { samples, primarySamples, isMSAA };
  46960. }
  46961. /**
  46962. * Returns the default color attachment's GPU format of the current render context.
  46963. *
  46964. * @param {RenderContext} renderContext - The render context.
  46965. * @return {string} The GPU texture format of the default color attachment.
  46966. */
  46967. getCurrentColorFormat( renderContext ) {
  46968. let format;
  46969. if ( renderContext.textures !== null ) {
  46970. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  46971. } else {
  46972. format = this.getPreferredCanvasFormat(); // default context format
  46973. }
  46974. return format;
  46975. }
  46976. /**
  46977. * Returns the output color space of the current render context.
  46978. *
  46979. * @param {RenderContext} renderContext - The render context.
  46980. * @return {string} The output color space.
  46981. */
  46982. getCurrentColorSpace( renderContext ) {
  46983. if ( renderContext.textures !== null ) {
  46984. return renderContext.textures[ 0 ].colorSpace;
  46985. }
  46986. return this.backend.renderer.outputColorSpace;
  46987. }
  46988. /**
  46989. * Returns GPU primitive topology for the given object and material.
  46990. *
  46991. * @param {Object3D} object - The 3D object.
  46992. * @param {Material} material - The material.
  46993. * @return {string} The GPU primitive topology.
  46994. */
  46995. getPrimitiveTopology( object, material ) {
  46996. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  46997. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  46998. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  46999. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  47000. }
  47001. /**
  47002. * Returns a modified sample count from the given sample count value.
  47003. *
  47004. * That is required since WebGPU does not support arbitrary sample counts.
  47005. *
  47006. * @param {number} sampleCount - The input sample count.
  47007. * @return {number} The (potentially updated) output sample count.
  47008. */
  47009. getSampleCount( sampleCount ) {
  47010. let count = 1;
  47011. if ( sampleCount > 1 ) {
  47012. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  47013. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  47014. if ( count === 2 ) {
  47015. count = 4;
  47016. }
  47017. }
  47018. return count;
  47019. }
  47020. /**
  47021. * Returns the sample count of the given render context.
  47022. *
  47023. * @param {RenderContext} renderContext - The render context.
  47024. * @return {number} The sample count.
  47025. */
  47026. getSampleCountRenderContext( renderContext ) {
  47027. if ( renderContext.textures !== null ) {
  47028. return this.getSampleCount( renderContext.sampleCount );
  47029. }
  47030. return this.getSampleCount( this.backend.renderer.samples );
  47031. }
  47032. /**
  47033. * Returns the preferred canvas format.
  47034. *
  47035. * There is a separate method for this so it's possible to
  47036. * honor edge cases for specific devices.
  47037. *
  47038. * @return {string} The GPU texture format of the canvas.
  47039. */
  47040. getPreferredCanvasFormat() {
  47041. const outputType = this.backend.parameters.outputType;
  47042. if ( outputType === undefined ) {
  47043. return navigator.gpu.getPreferredCanvasFormat();
  47044. } else if ( outputType === UnsignedByteType ) {
  47045. return GPUTextureFormat.BGRA8Unorm;
  47046. } else if ( outputType === HalfFloatType ) {
  47047. return GPUTextureFormat.RGBA16Float;
  47048. } else {
  47049. throw new Error( 'Unsupported outputType' );
  47050. }
  47051. }
  47052. }
  47053. const typedArraysToVertexFormatPrefix = new Map( [
  47054. [ Int8Array, [ 'sint8', 'snorm8' ]],
  47055. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  47056. [ Int16Array, [ 'sint16', 'snorm16' ]],
  47057. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  47058. [ Int32Array, [ 'sint32', 'snorm32' ]],
  47059. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  47060. [ Float32Array, [ 'float32', ]],
  47061. ] );
  47062. const typedAttributeToVertexFormatPrefix = new Map( [
  47063. [ Float16BufferAttribute, [ 'float16', ]],
  47064. ] );
  47065. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  47066. [ Int32Array, 'sint32' ],
  47067. [ Int16Array, 'sint32' ], // patch for INT16
  47068. [ Uint32Array, 'uint32' ],
  47069. [ Uint16Array, 'uint32' ], // patch for UINT16
  47070. [ Float32Array, 'float32' ]
  47071. ] );
  47072. /**
  47073. * A WebGPU backend utility module for managing shader attributes.
  47074. *
  47075. * @private
  47076. */
  47077. class WebGPUAttributeUtils {
  47078. /**
  47079. * Constructs a new utility object.
  47080. *
  47081. * @param {WebGPUBackend} backend - The WebGPU backend.
  47082. */
  47083. constructor( backend ) {
  47084. /**
  47085. * A reference to the WebGPU backend.
  47086. *
  47087. * @type {WebGPUBackend}
  47088. */
  47089. this.backend = backend;
  47090. }
  47091. /**
  47092. * Creates the GPU buffer for the given buffer attribute.
  47093. *
  47094. * @param {BufferAttribute} attribute - The buffer attribute.
  47095. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  47096. */
  47097. createAttribute( attribute, usage ) {
  47098. const bufferAttribute = this._getBufferAttribute( attribute );
  47099. const backend = this.backend;
  47100. const bufferData = backend.get( bufferAttribute );
  47101. let buffer = bufferData.buffer;
  47102. if ( buffer === undefined ) {
  47103. const device = backend.device;
  47104. let array = bufferAttribute.array;
  47105. // patch for INT16 and UINT16
  47106. if ( attribute.normalized === false ) {
  47107. if ( array.constructor === Int16Array ) {
  47108. array = new Int32Array( array );
  47109. } else if ( array.constructor === Uint16Array ) {
  47110. array = new Uint32Array( array );
  47111. if ( usage & GPUBufferUsage.INDEX ) {
  47112. for ( let i = 0; i < array.length; i ++ ) {
  47113. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  47114. }
  47115. }
  47116. }
  47117. }
  47118. bufferAttribute.array = array;
  47119. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  47120. array = new array.constructor( bufferAttribute.count * 4 );
  47121. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  47122. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  47123. }
  47124. // Update BufferAttribute
  47125. bufferAttribute.itemSize = 4;
  47126. bufferAttribute.array = array;
  47127. bufferData._force3to4BytesAlignment = true;
  47128. }
  47129. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  47130. buffer = device.createBuffer( {
  47131. label: bufferAttribute.name,
  47132. size: size,
  47133. usage: usage,
  47134. mappedAtCreation: true
  47135. } );
  47136. new array.constructor( buffer.getMappedRange() ).set( array );
  47137. buffer.unmap();
  47138. bufferData.buffer = buffer;
  47139. }
  47140. }
  47141. /**
  47142. * Updates the GPU buffer of the given buffer attribute.
  47143. *
  47144. * @param {BufferAttribute} attribute - The buffer attribute.
  47145. */
  47146. updateAttribute( attribute ) {
  47147. const bufferAttribute = this._getBufferAttribute( attribute );
  47148. const backend = this.backend;
  47149. const device = backend.device;
  47150. const bufferData = backend.get( bufferAttribute );
  47151. const buffer = backend.get( bufferAttribute ).buffer;
  47152. let array = bufferAttribute.array;
  47153. // if storage buffer ensure 4 byte alignment
  47154. if ( bufferData._force3to4BytesAlignment === true ) {
  47155. array = new array.constructor( bufferAttribute.count * 4 );
  47156. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  47157. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  47158. }
  47159. bufferAttribute.array = array;
  47160. }
  47161. const isTypedArray = this._isTypedArray( array );
  47162. const updateRanges = bufferAttribute.updateRanges;
  47163. if ( updateRanges.length === 0 ) {
  47164. // Not using update ranges
  47165. device.queue.writeBuffer(
  47166. buffer,
  47167. 0,
  47168. array,
  47169. 0
  47170. );
  47171. } else {
  47172. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  47173. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  47174. const range = updateRanges[ i ];
  47175. let dataOffset, size;
  47176. if ( bufferData._force3to4BytesAlignment === true ) {
  47177. const vertexStart = Math.floor( range.start / 3 );
  47178. const vertexCount = Math.ceil( range.count / 3 );
  47179. dataOffset = vertexStart * 4 * byteOffsetFactor;
  47180. size = vertexCount * 4 * byteOffsetFactor;
  47181. } else {
  47182. dataOffset = range.start * byteOffsetFactor;
  47183. size = range.count * byteOffsetFactor;
  47184. }
  47185. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  47186. device.queue.writeBuffer(
  47187. buffer,
  47188. bufferOffset,
  47189. array,
  47190. dataOffset,
  47191. size
  47192. );
  47193. }
  47194. bufferAttribute.clearUpdateRanges();
  47195. }
  47196. }
  47197. /**
  47198. * This method creates the vertex buffer layout data which are
  47199. * require when creating a render pipeline for the given render object.
  47200. *
  47201. * @param {RenderObject} renderObject - The render object.
  47202. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  47203. */
  47204. createShaderVertexBuffers( renderObject ) {
  47205. const attributes = renderObject.getAttributes();
  47206. const vertexBuffers = new Map();
  47207. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  47208. const geometryAttribute = attributes[ slot ];
  47209. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  47210. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  47211. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  47212. if ( vertexBufferLayout === undefined ) {
  47213. let arrayStride, stepMode;
  47214. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  47215. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  47216. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  47217. } else {
  47218. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  47219. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  47220. }
  47221. // patch for INT16 and UINT16
  47222. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  47223. arrayStride = 4;
  47224. }
  47225. vertexBufferLayout = {
  47226. arrayStride,
  47227. attributes: [],
  47228. stepMode
  47229. };
  47230. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  47231. }
  47232. const format = this._getVertexFormat( geometryAttribute );
  47233. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  47234. vertexBufferLayout.attributes.push( {
  47235. shaderLocation: slot,
  47236. offset,
  47237. format
  47238. } );
  47239. }
  47240. return Array.from( vertexBuffers.values() );
  47241. }
  47242. /**
  47243. * Destroys the GPU buffer of the given buffer attribute.
  47244. *
  47245. * @param {BufferAttribute} attribute - The buffer attribute.
  47246. */
  47247. destroyAttribute( attribute ) {
  47248. const backend = this.backend;
  47249. const data = backend.get( this._getBufferAttribute( attribute ) );
  47250. data.buffer.destroy();
  47251. backend.delete( attribute );
  47252. }
  47253. /**
  47254. * This method performs a readback operation by moving buffer data from
  47255. * a storage buffer attribute from the GPU to the CPU.
  47256. *
  47257. * @async
  47258. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  47259. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  47260. */
  47261. async getArrayBufferAsync( attribute ) {
  47262. const backend = this.backend;
  47263. const device = backend.device;
  47264. const data = backend.get( this._getBufferAttribute( attribute ) );
  47265. const bufferGPU = data.buffer;
  47266. const size = bufferGPU.size;
  47267. const readBufferGPU = device.createBuffer( {
  47268. label: `${ attribute.name }_readback`,
  47269. size,
  47270. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47271. } );
  47272. const cmdEncoder = device.createCommandEncoder( {
  47273. label: `readback_encoder_${ attribute.name }`
  47274. } );
  47275. cmdEncoder.copyBufferToBuffer(
  47276. bufferGPU,
  47277. 0,
  47278. readBufferGPU,
  47279. 0,
  47280. size
  47281. );
  47282. const gpuCommands = cmdEncoder.finish();
  47283. device.queue.submit( [ gpuCommands ] );
  47284. await readBufferGPU.mapAsync( GPUMapMode.READ );
  47285. const arrayBuffer = readBufferGPU.getMappedRange();
  47286. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  47287. readBufferGPU.unmap();
  47288. return dstBuffer.buffer;
  47289. }
  47290. /**
  47291. * Returns the vertex format of the given buffer attribute.
  47292. *
  47293. * @private
  47294. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  47295. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  47296. */
  47297. _getVertexFormat( geometryAttribute ) {
  47298. const { itemSize, normalized } = geometryAttribute;
  47299. const ArrayType = geometryAttribute.array.constructor;
  47300. const AttributeType = geometryAttribute.constructor;
  47301. let format;
  47302. if ( itemSize === 1 ) {
  47303. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  47304. } else {
  47305. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  47306. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  47307. if ( prefix ) {
  47308. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  47309. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  47310. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  47311. if ( paddedItemSize % 1 ) {
  47312. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  47313. }
  47314. format = `${prefix}x${paddedItemSize}`;
  47315. }
  47316. }
  47317. if ( ! format ) {
  47318. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  47319. }
  47320. return format;
  47321. }
  47322. /**
  47323. * Returns `true` if the given array is a typed array.
  47324. *
  47325. * @private
  47326. * @param {any} array - The array.
  47327. * @return {boolean} Whether the given array is a typed array or not.
  47328. */
  47329. _isTypedArray( array ) {
  47330. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  47331. }
  47332. /**
  47333. * Utility method for handling interleaved buffer attributes correctly.
  47334. * To process them, their `InterleavedBuffer` is returned.
  47335. *
  47336. * @private
  47337. * @param {BufferAttribute} attribute - The attribute.
  47338. * @return {BufferAttribute|InterleavedBuffer}
  47339. */
  47340. _getBufferAttribute( attribute ) {
  47341. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  47342. return attribute;
  47343. }
  47344. }
  47345. /**
  47346. * A WebGPU backend utility module for managing bindings.
  47347. *
  47348. * When reading the documentation it's helpful to keep in mind that
  47349. * all class definitions starting with 'GPU*' are modules from the
  47350. * WebGPU API. So for example `BindGroup` is a class from the engine
  47351. * whereas `GPUBindGroup` is a class from WebGPU.
  47352. *
  47353. * @private
  47354. */
  47355. class WebGPUBindingUtils {
  47356. /**
  47357. * Constructs a new utility object.
  47358. *
  47359. * @param {WebGPUBackend} backend - The WebGPU backend.
  47360. */
  47361. constructor( backend ) {
  47362. /**
  47363. * A reference to the WebGPU backend.
  47364. *
  47365. * @type {WebGPUBackend}
  47366. */
  47367. this.backend = backend;
  47368. /**
  47369. * A cache for managing bind group layouts.
  47370. *
  47371. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  47372. */
  47373. this.bindGroupLayoutCache = new WeakMap();
  47374. }
  47375. /**
  47376. * Creates a GPU bind group layout for the given bind group.
  47377. *
  47378. * @param {BindGroup} bindGroup - The bind group.
  47379. * @return {GPUBindGroupLayout} The GPU bind group layout.
  47380. */
  47381. createBindingsLayout( bindGroup ) {
  47382. const backend = this.backend;
  47383. const device = backend.device;
  47384. const entries = [];
  47385. let index = 0;
  47386. for ( const binding of bindGroup.bindings ) {
  47387. const bindingGPU = {
  47388. binding: index ++,
  47389. visibility: binding.visibility
  47390. };
  47391. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  47392. const buffer = {}; // GPUBufferBindingLayout
  47393. if ( binding.isStorageBuffer ) {
  47394. if ( binding.visibility & 4 ) {
  47395. // compute
  47396. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  47397. buffer.type = GPUBufferBindingType.Storage;
  47398. } else {
  47399. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  47400. }
  47401. } else {
  47402. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  47403. }
  47404. }
  47405. bindingGPU.buffer = buffer;
  47406. } else if ( binding.isSampler ) {
  47407. const sampler = {}; // GPUSamplerBindingLayout
  47408. if ( binding.texture.isDepthTexture ) {
  47409. if ( binding.texture.compareFunction !== null ) {
  47410. sampler.type = 'comparison';
  47411. }
  47412. }
  47413. bindingGPU.sampler = sampler;
  47414. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  47415. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  47416. } else if ( binding.isSampledTexture && binding.store ) {
  47417. const storageTexture = {}; // GPUStorageTextureBindingLayout
  47418. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  47419. const access = binding.access;
  47420. if ( access === NodeAccess.READ_WRITE ) {
  47421. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  47422. } else if ( access === NodeAccess.WRITE_ONLY ) {
  47423. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  47424. } else {
  47425. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  47426. }
  47427. bindingGPU.storageTexture = storageTexture;
  47428. } else if ( binding.isSampledTexture ) {
  47429. const texture = {}; // GPUTextureBindingLayout
  47430. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  47431. if ( primarySamples > 1 ) {
  47432. texture.multisampled = true;
  47433. if ( ! binding.texture.isDepthTexture ) {
  47434. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  47435. }
  47436. }
  47437. if ( binding.texture.isDepthTexture ) {
  47438. texture.sampleType = GPUTextureSampleType.Depth;
  47439. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  47440. const type = binding.texture.type;
  47441. if ( type === IntType ) {
  47442. texture.sampleType = GPUTextureSampleType.SInt;
  47443. } else if ( type === UnsignedIntType ) {
  47444. texture.sampleType = GPUTextureSampleType.UInt;
  47445. } else if ( type === FloatType ) {
  47446. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  47447. texture.sampleType = GPUTextureSampleType.Float;
  47448. } else {
  47449. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  47450. }
  47451. }
  47452. }
  47453. if ( binding.isSampledCubeTexture ) {
  47454. texture.viewDimension = GPUTextureViewDimension.Cube;
  47455. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  47456. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  47457. } else if ( binding.isSampledTexture3D ) {
  47458. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  47459. }
  47460. bindingGPU.texture = texture;
  47461. } else {
  47462. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  47463. }
  47464. entries.push( bindingGPU );
  47465. }
  47466. return device.createBindGroupLayout( { entries } );
  47467. }
  47468. /**
  47469. * Creates bindings from the given bind group definition.
  47470. *
  47471. * @param {BindGroup} bindGroup - The bind group.
  47472. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47473. * @param {number} cacheIndex - The cache index.
  47474. * @param {number} version - The version.
  47475. */
  47476. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  47477. const { backend, bindGroupLayoutCache } = this;
  47478. const bindingsData = backend.get( bindGroup );
  47479. // setup (static) binding layout and (dynamic) binding group
  47480. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  47481. if ( bindLayoutGPU === undefined ) {
  47482. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  47483. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  47484. }
  47485. let bindGroupGPU;
  47486. if ( cacheIndex > 0 ) {
  47487. if ( bindingsData.groups === undefined ) {
  47488. bindingsData.groups = [];
  47489. bindingsData.versions = [];
  47490. }
  47491. if ( bindingsData.versions[ cacheIndex ] === version ) {
  47492. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  47493. }
  47494. }
  47495. if ( bindGroupGPU === undefined ) {
  47496. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  47497. if ( cacheIndex > 0 ) {
  47498. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  47499. bindingsData.versions[ cacheIndex ] = version;
  47500. }
  47501. }
  47502. bindingsData.group = bindGroupGPU;
  47503. bindingsData.layout = bindLayoutGPU;
  47504. }
  47505. /**
  47506. * Updates a buffer binding.
  47507. *
  47508. * @param {Buffer} binding - The buffer binding to update.
  47509. */
  47510. updateBinding( binding ) {
  47511. const backend = this.backend;
  47512. const device = backend.device;
  47513. const buffer = binding.buffer;
  47514. const bufferGPU = backend.get( binding ).buffer;
  47515. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  47516. }
  47517. /**
  47518. * Creates a GPU bind group for the camera index.
  47519. *
  47520. * @param {Uint32Array} data - The index data.
  47521. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  47522. * @return {GPUBindGroup} The GPU bind group.
  47523. */
  47524. createBindGroupIndex( data, layout ) {
  47525. const backend = this.backend;
  47526. const device = backend.device;
  47527. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  47528. const index = data[ 0 ];
  47529. const buffer = device.createBuffer( {
  47530. label: 'bindingCameraIndex_' + index,
  47531. size: 16, // uint(4) * 4
  47532. usage: usage
  47533. } );
  47534. device.queue.writeBuffer( buffer, 0, data, 0 );
  47535. const entries = [ { binding: 0, resource: { buffer } } ];
  47536. return device.createBindGroup( {
  47537. label: 'bindGroupCameraIndex_' + index,
  47538. layout,
  47539. entries
  47540. } );
  47541. }
  47542. /**
  47543. * Creates a GPU bind group for the given bind group and GPU layout.
  47544. *
  47545. * @param {BindGroup} bindGroup - The bind group.
  47546. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  47547. * @return {GPUBindGroup} The GPU bind group.
  47548. */
  47549. createBindGroup( bindGroup, layoutGPU ) {
  47550. const backend = this.backend;
  47551. const device = backend.device;
  47552. let bindingPoint = 0;
  47553. const entriesGPU = [];
  47554. for ( const binding of bindGroup.bindings ) {
  47555. if ( binding.isUniformBuffer ) {
  47556. const bindingData = backend.get( binding );
  47557. if ( bindingData.buffer === undefined ) {
  47558. const byteLength = binding.byteLength;
  47559. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  47560. const bufferGPU = device.createBuffer( {
  47561. label: 'bindingBuffer_' + binding.name,
  47562. size: byteLength,
  47563. usage: usage
  47564. } );
  47565. bindingData.buffer = bufferGPU;
  47566. }
  47567. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  47568. } else if ( binding.isStorageBuffer ) {
  47569. const bindingData = backend.get( binding );
  47570. if ( bindingData.buffer === undefined ) {
  47571. const attribute = binding.attribute;
  47572. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  47573. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  47574. bindingData.buffer = backend.get( attribute ).buffer;
  47575. }
  47576. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  47577. } else if ( binding.isSampler ) {
  47578. const textureGPU = backend.get( binding.texture );
  47579. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  47580. } else if ( binding.isSampledTexture ) {
  47581. const textureData = backend.get( binding.texture );
  47582. let resourceGPU;
  47583. if ( textureData.externalTexture !== undefined ) {
  47584. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  47585. } else {
  47586. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  47587. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  47588. resourceGPU = textureData[ propertyName ];
  47589. if ( resourceGPU === undefined ) {
  47590. const aspectGPU = GPUTextureAspect.All;
  47591. let dimensionViewGPU;
  47592. if ( binding.isSampledCubeTexture ) {
  47593. dimensionViewGPU = GPUTextureViewDimension.Cube;
  47594. } else if ( binding.isSampledTexture3D ) {
  47595. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  47596. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  47597. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  47598. } else {
  47599. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  47600. }
  47601. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  47602. }
  47603. }
  47604. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  47605. }
  47606. bindingPoint ++;
  47607. }
  47608. return device.createBindGroup( {
  47609. label: 'bindGroup_' + bindGroup.name,
  47610. layout: layoutGPU,
  47611. entries: entriesGPU
  47612. } );
  47613. }
  47614. }
  47615. /**
  47616. * A WebGPU backend utility module for managing pipelines.
  47617. *
  47618. * @private
  47619. */
  47620. class WebGPUPipelineUtils {
  47621. /**
  47622. * Constructs a new utility object.
  47623. *
  47624. * @param {WebGPUBackend} backend - The WebGPU backend.
  47625. */
  47626. constructor( backend ) {
  47627. /**
  47628. * A reference to the WebGPU backend.
  47629. *
  47630. * @type {WebGPUBackend}
  47631. */
  47632. this.backend = backend;
  47633. }
  47634. /**
  47635. * Returns the sample count derived from the given render context.
  47636. *
  47637. * @private
  47638. * @param {RenderContext} renderContext - The render context.
  47639. * @return {number} The sample count.
  47640. */
  47641. _getSampleCount( renderContext ) {
  47642. return this.backend.utils.getSampleCountRenderContext( renderContext );
  47643. }
  47644. /**
  47645. * Creates a render pipeline for the given render object.
  47646. *
  47647. * @param {RenderObject} renderObject - The render object.
  47648. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47649. */
  47650. createRenderPipeline( renderObject, promises ) {
  47651. const { object, material, geometry, pipeline } = renderObject;
  47652. const { vertexProgram, fragmentProgram } = pipeline;
  47653. const backend = this.backend;
  47654. const device = backend.device;
  47655. const utils = backend.utils;
  47656. const pipelineData = backend.get( pipeline );
  47657. // bind group layouts
  47658. const bindGroupLayouts = [];
  47659. for ( const bindGroup of renderObject.getBindings() ) {
  47660. const bindingsData = backend.get( bindGroup );
  47661. bindGroupLayouts.push( bindingsData.layout );
  47662. }
  47663. // vertex buffers
  47664. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  47665. // blending
  47666. let blending;
  47667. if ( material.transparent === true && material.blending !== NoBlending ) {
  47668. blending = this._getBlending( material );
  47669. }
  47670. // stencil
  47671. let stencilFront = {};
  47672. if ( material.stencilWrite === true ) {
  47673. stencilFront = {
  47674. compare: this._getStencilCompare( material ),
  47675. failOp: this._getStencilOperation( material.stencilFail ),
  47676. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  47677. passOp: this._getStencilOperation( material.stencilZPass )
  47678. };
  47679. }
  47680. const colorWriteMask = this._getColorWriteMask( material );
  47681. const targets = [];
  47682. if ( renderObject.context.textures !== null ) {
  47683. const textures = renderObject.context.textures;
  47684. for ( let i = 0; i < textures.length; i ++ ) {
  47685. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  47686. targets.push( {
  47687. format: colorFormat,
  47688. blend: blending,
  47689. writeMask: colorWriteMask
  47690. } );
  47691. }
  47692. } else {
  47693. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  47694. targets.push( {
  47695. format: colorFormat,
  47696. blend: blending,
  47697. writeMask: colorWriteMask
  47698. } );
  47699. }
  47700. const vertexModule = backend.get( vertexProgram ).module;
  47701. const fragmentModule = backend.get( fragmentProgram ).module;
  47702. const primitiveState = this._getPrimitiveState( object, geometry, material );
  47703. const depthCompare = this._getDepthCompare( material );
  47704. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  47705. const sampleCount = this._getSampleCount( renderObject.context );
  47706. const pipelineDescriptor = {
  47707. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  47708. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  47709. fragment: Object.assign( {}, fragmentModule, { targets } ),
  47710. primitive: primitiveState,
  47711. multisample: {
  47712. count: sampleCount,
  47713. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  47714. },
  47715. layout: device.createPipelineLayout( {
  47716. bindGroupLayouts
  47717. } )
  47718. };
  47719. const depthStencil = {};
  47720. const renderDepth = renderObject.context.depth;
  47721. const renderStencil = renderObject.context.stencil;
  47722. if ( renderDepth === true || renderStencil === true ) {
  47723. if ( renderDepth === true ) {
  47724. depthStencil.format = depthStencilFormat;
  47725. depthStencil.depthWriteEnabled = material.depthWrite;
  47726. depthStencil.depthCompare = depthCompare;
  47727. }
  47728. if ( renderStencil === true ) {
  47729. depthStencil.stencilFront = stencilFront;
  47730. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  47731. depthStencil.stencilReadMask = material.stencilFuncMask;
  47732. depthStencil.stencilWriteMask = material.stencilWriteMask;
  47733. }
  47734. if ( material.polygonOffset === true ) {
  47735. depthStencil.depthBias = material.polygonOffsetUnits;
  47736. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  47737. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  47738. }
  47739. pipelineDescriptor.depthStencil = depthStencil;
  47740. }
  47741. if ( promises === null ) {
  47742. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  47743. } else {
  47744. const p = new Promise( ( resolve /*, reject*/ ) => {
  47745. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  47746. pipelineData.pipeline = pipeline;
  47747. resolve();
  47748. } );
  47749. } );
  47750. promises.push( p );
  47751. }
  47752. }
  47753. /**
  47754. * Creates GPU render bundle encoder for the given render context.
  47755. *
  47756. * @param {RenderContext} renderContext - The render context.
  47757. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  47758. */
  47759. createBundleEncoder( renderContext ) {
  47760. const backend = this.backend;
  47761. const { utils, device } = backend;
  47762. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  47763. const colorFormat = utils.getCurrentColorFormat( renderContext );
  47764. const sampleCount = this._getSampleCount( renderContext );
  47765. const descriptor = {
  47766. label: 'renderBundleEncoder',
  47767. colorFormats: [ colorFormat ],
  47768. depthStencilFormat,
  47769. sampleCount
  47770. };
  47771. return device.createRenderBundleEncoder( descriptor );
  47772. }
  47773. /**
  47774. * Creates a compute pipeline for the given compute node.
  47775. *
  47776. * @param {ComputePipeline} pipeline - The compute pipeline.
  47777. * @param {Array<BindGroup>} bindings - The bindings.
  47778. */
  47779. createComputePipeline( pipeline, bindings ) {
  47780. const backend = this.backend;
  47781. const device = backend.device;
  47782. const computeProgram = backend.get( pipeline.computeProgram ).module;
  47783. const pipelineGPU = backend.get( pipeline );
  47784. // bind group layouts
  47785. const bindGroupLayouts = [];
  47786. for ( const bindingsGroup of bindings ) {
  47787. const bindingsData = backend.get( bindingsGroup );
  47788. bindGroupLayouts.push( bindingsData.layout );
  47789. }
  47790. pipelineGPU.pipeline = device.createComputePipeline( {
  47791. compute: computeProgram,
  47792. layout: device.createPipelineLayout( {
  47793. bindGroupLayouts
  47794. } )
  47795. } );
  47796. }
  47797. /**
  47798. * Returns the blending state as a descriptor object required
  47799. * for the pipeline creation.
  47800. *
  47801. * @private
  47802. * @param {Material} material - The material.
  47803. * @return {Object} The blending state.
  47804. */
  47805. _getBlending( material ) {
  47806. let color, alpha;
  47807. const blending = material.blending;
  47808. const blendSrc = material.blendSrc;
  47809. const blendDst = material.blendDst;
  47810. const blendEquation = material.blendEquation;
  47811. if ( blending === CustomBlending ) {
  47812. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  47813. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  47814. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  47815. color = {
  47816. srcFactor: this._getBlendFactor( blendSrc ),
  47817. dstFactor: this._getBlendFactor( blendDst ),
  47818. operation: this._getBlendOperation( blendEquation )
  47819. };
  47820. alpha = {
  47821. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  47822. dstFactor: this._getBlendFactor( blendDstAlpha ),
  47823. operation: this._getBlendOperation( blendEquationAlpha )
  47824. };
  47825. } else {
  47826. const premultipliedAlpha = material.premultipliedAlpha;
  47827. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  47828. color = {
  47829. srcFactor: srcRGB,
  47830. dstFactor: dstRGB,
  47831. operation: GPUBlendOperation.Add
  47832. };
  47833. alpha = {
  47834. srcFactor: srcAlpha,
  47835. dstFactor: dstAlpha,
  47836. operation: GPUBlendOperation.Add
  47837. };
  47838. };
  47839. if ( premultipliedAlpha ) {
  47840. switch ( blending ) {
  47841. case NormalBlending:
  47842. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  47843. break;
  47844. case AdditiveBlending:
  47845. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  47846. break;
  47847. case SubtractiveBlending:
  47848. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  47849. break;
  47850. case MultiplyBlending:
  47851. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  47852. break;
  47853. }
  47854. } else {
  47855. switch ( blending ) {
  47856. case NormalBlending:
  47857. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  47858. break;
  47859. case AdditiveBlending:
  47860. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  47861. break;
  47862. case SubtractiveBlending:
  47863. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  47864. break;
  47865. case MultiplyBlending:
  47866. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  47867. break;
  47868. }
  47869. }
  47870. }
  47871. if ( color !== undefined && alpha !== undefined ) {
  47872. return { color, alpha };
  47873. } else {
  47874. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  47875. }
  47876. }
  47877. /**
  47878. * Returns the GPU blend factor which is required for the pipeline creation.
  47879. *
  47880. * @private
  47881. * @param {number} blend - The blend factor as a three.js constant.
  47882. * @return {string} The GPU blend factor.
  47883. */
  47884. _getBlendFactor( blend ) {
  47885. let blendFactor;
  47886. switch ( blend ) {
  47887. case ZeroFactor:
  47888. blendFactor = GPUBlendFactor.Zero;
  47889. break;
  47890. case OneFactor:
  47891. blendFactor = GPUBlendFactor.One;
  47892. break;
  47893. case SrcColorFactor:
  47894. blendFactor = GPUBlendFactor.Src;
  47895. break;
  47896. case OneMinusSrcColorFactor:
  47897. blendFactor = GPUBlendFactor.OneMinusSrc;
  47898. break;
  47899. case SrcAlphaFactor:
  47900. blendFactor = GPUBlendFactor.SrcAlpha;
  47901. break;
  47902. case OneMinusSrcAlphaFactor:
  47903. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  47904. break;
  47905. case DstColorFactor:
  47906. blendFactor = GPUBlendFactor.Dst;
  47907. break;
  47908. case OneMinusDstColorFactor:
  47909. blendFactor = GPUBlendFactor.OneMinusDstColor;
  47910. break;
  47911. case DstAlphaFactor:
  47912. blendFactor = GPUBlendFactor.DstAlpha;
  47913. break;
  47914. case OneMinusDstAlphaFactor:
  47915. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  47916. break;
  47917. case SrcAlphaSaturateFactor:
  47918. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  47919. break;
  47920. case BlendColorFactor:
  47921. blendFactor = GPUBlendFactor.Constant;
  47922. break;
  47923. case OneMinusBlendColorFactor:
  47924. blendFactor = GPUBlendFactor.OneMinusConstant;
  47925. break;
  47926. default:
  47927. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  47928. }
  47929. return blendFactor;
  47930. }
  47931. /**
  47932. * Returns the GPU stencil compare function which is required for the pipeline creation.
  47933. *
  47934. * @private
  47935. * @param {Material} material - The material.
  47936. * @return {string} The GPU stencil compare function.
  47937. */
  47938. _getStencilCompare( material ) {
  47939. let stencilCompare;
  47940. const stencilFunc = material.stencilFunc;
  47941. switch ( stencilFunc ) {
  47942. case NeverStencilFunc:
  47943. stencilCompare = GPUCompareFunction.Never;
  47944. break;
  47945. case AlwaysStencilFunc:
  47946. stencilCompare = GPUCompareFunction.Always;
  47947. break;
  47948. case LessStencilFunc:
  47949. stencilCompare = GPUCompareFunction.Less;
  47950. break;
  47951. case LessEqualStencilFunc:
  47952. stencilCompare = GPUCompareFunction.LessEqual;
  47953. break;
  47954. case EqualStencilFunc:
  47955. stencilCompare = GPUCompareFunction.Equal;
  47956. break;
  47957. case GreaterEqualStencilFunc:
  47958. stencilCompare = GPUCompareFunction.GreaterEqual;
  47959. break;
  47960. case GreaterStencilFunc:
  47961. stencilCompare = GPUCompareFunction.Greater;
  47962. break;
  47963. case NotEqualStencilFunc:
  47964. stencilCompare = GPUCompareFunction.NotEqual;
  47965. break;
  47966. default:
  47967. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  47968. }
  47969. return stencilCompare;
  47970. }
  47971. /**
  47972. * Returns the GPU stencil operation which is required for the pipeline creation.
  47973. *
  47974. * @private
  47975. * @param {number} op - A three.js constant defining the stencil operation.
  47976. * @return {string} The GPU stencil operation.
  47977. */
  47978. _getStencilOperation( op ) {
  47979. let stencilOperation;
  47980. switch ( op ) {
  47981. case KeepStencilOp:
  47982. stencilOperation = GPUStencilOperation.Keep;
  47983. break;
  47984. case ZeroStencilOp:
  47985. stencilOperation = GPUStencilOperation.Zero;
  47986. break;
  47987. case ReplaceStencilOp:
  47988. stencilOperation = GPUStencilOperation.Replace;
  47989. break;
  47990. case InvertStencilOp:
  47991. stencilOperation = GPUStencilOperation.Invert;
  47992. break;
  47993. case IncrementStencilOp:
  47994. stencilOperation = GPUStencilOperation.IncrementClamp;
  47995. break;
  47996. case DecrementStencilOp:
  47997. stencilOperation = GPUStencilOperation.DecrementClamp;
  47998. break;
  47999. case IncrementWrapStencilOp:
  48000. stencilOperation = GPUStencilOperation.IncrementWrap;
  48001. break;
  48002. case DecrementWrapStencilOp:
  48003. stencilOperation = GPUStencilOperation.DecrementWrap;
  48004. break;
  48005. default:
  48006. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  48007. }
  48008. return stencilOperation;
  48009. }
  48010. /**
  48011. * Returns the GPU blend operation which is required for the pipeline creation.
  48012. *
  48013. * @private
  48014. * @param {number} blendEquation - A three.js constant defining the blend equation.
  48015. * @return {string} The GPU blend operation.
  48016. */
  48017. _getBlendOperation( blendEquation ) {
  48018. let blendOperation;
  48019. switch ( blendEquation ) {
  48020. case AddEquation:
  48021. blendOperation = GPUBlendOperation.Add;
  48022. break;
  48023. case SubtractEquation:
  48024. blendOperation = GPUBlendOperation.Subtract;
  48025. break;
  48026. case ReverseSubtractEquation:
  48027. blendOperation = GPUBlendOperation.ReverseSubtract;
  48028. break;
  48029. case MinEquation:
  48030. blendOperation = GPUBlendOperation.Min;
  48031. break;
  48032. case MaxEquation:
  48033. blendOperation = GPUBlendOperation.Max;
  48034. break;
  48035. default:
  48036. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  48037. }
  48038. return blendOperation;
  48039. }
  48040. /**
  48041. * Returns the primitive state as a descriptor object required
  48042. * for the pipeline creation.
  48043. *
  48044. * @private
  48045. * @param {Object3D} object - The 3D object.
  48046. * @param {BufferGeometry} geometry - The geometry.
  48047. * @param {Material} material - The material.
  48048. * @return {Object} The primitive state.
  48049. */
  48050. _getPrimitiveState( object, geometry, material ) {
  48051. const descriptor = {};
  48052. const utils = this.backend.utils;
  48053. descriptor.topology = utils.getPrimitiveTopology( object, material );
  48054. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  48055. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  48056. }
  48057. switch ( material.side ) {
  48058. case FrontSide:
  48059. descriptor.frontFace = GPUFrontFace.CCW;
  48060. descriptor.cullMode = GPUCullMode.Back;
  48061. break;
  48062. case BackSide:
  48063. descriptor.frontFace = GPUFrontFace.CCW;
  48064. descriptor.cullMode = GPUCullMode.Front;
  48065. break;
  48066. case DoubleSide:
  48067. descriptor.frontFace = GPUFrontFace.CCW;
  48068. descriptor.cullMode = GPUCullMode.None;
  48069. break;
  48070. default:
  48071. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  48072. break;
  48073. }
  48074. return descriptor;
  48075. }
  48076. /**
  48077. * Returns the GPU color write mask which is required for the pipeline creation.
  48078. *
  48079. * @private
  48080. * @param {Material} material - The material.
  48081. * @return {string} The GPU color write mask.
  48082. */
  48083. _getColorWriteMask( material ) {
  48084. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  48085. }
  48086. /**
  48087. * Returns the GPU depth compare function which is required for the pipeline creation.
  48088. *
  48089. * @private
  48090. * @param {Material} material - The material.
  48091. * @return {string} The GPU depth compare function.
  48092. */
  48093. _getDepthCompare( material ) {
  48094. let depthCompare;
  48095. if ( material.depthTest === false ) {
  48096. depthCompare = GPUCompareFunction.Always;
  48097. } else {
  48098. const depthFunc = material.depthFunc;
  48099. switch ( depthFunc ) {
  48100. case NeverDepth:
  48101. depthCompare = GPUCompareFunction.Never;
  48102. break;
  48103. case AlwaysDepth:
  48104. depthCompare = GPUCompareFunction.Always;
  48105. break;
  48106. case LessDepth:
  48107. depthCompare = GPUCompareFunction.Less;
  48108. break;
  48109. case LessEqualDepth:
  48110. depthCompare = GPUCompareFunction.LessEqual;
  48111. break;
  48112. case EqualDepth:
  48113. depthCompare = GPUCompareFunction.Equal;
  48114. break;
  48115. case GreaterEqualDepth:
  48116. depthCompare = GPUCompareFunction.GreaterEqual;
  48117. break;
  48118. case GreaterDepth:
  48119. depthCompare = GPUCompareFunction.Greater;
  48120. break;
  48121. case NotEqualDepth:
  48122. depthCompare = GPUCompareFunction.NotEqual;
  48123. break;
  48124. default:
  48125. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  48126. }
  48127. }
  48128. return depthCompare;
  48129. }
  48130. }
  48131. /**
  48132. * Manages a pool of WebGPU timestamp queries for performance measurement.
  48133. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  48134. *
  48135. * @augments TimestampQueryPool
  48136. */
  48137. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  48138. /**
  48139. * Creates a new WebGPU timestamp query pool.
  48140. *
  48141. * @param {GPUDevice} device - The WebGPU device to create queries on.
  48142. * @param {string} type - The type identifier for this query pool.
  48143. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  48144. */
  48145. constructor( device, type, maxQueries = 2048 ) {
  48146. super( maxQueries );
  48147. this.device = device;
  48148. this.type = type;
  48149. this.querySet = this.device.createQuerySet( {
  48150. type: 'timestamp',
  48151. count: this.maxQueries,
  48152. label: `queryset_global_timestamp_${type}`
  48153. } );
  48154. const bufferSize = this.maxQueries * 8;
  48155. this.resolveBuffer = this.device.createBuffer( {
  48156. label: `buffer_timestamp_resolve_${type}`,
  48157. size: bufferSize,
  48158. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  48159. } );
  48160. this.resultBuffer = this.device.createBuffer( {
  48161. label: `buffer_timestamp_result_${type}`,
  48162. size: bufferSize,
  48163. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48164. } );
  48165. }
  48166. /**
  48167. * Allocates a pair of queries for a given render context.
  48168. *
  48169. * @param {Object} renderContext - The render context to allocate queries for.
  48170. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  48171. */
  48172. allocateQueriesForContext( renderContext ) {
  48173. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  48174. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  48175. 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() } ).` );
  48176. return null;
  48177. }
  48178. const baseOffset = this.currentQueryIndex;
  48179. this.currentQueryIndex += 2;
  48180. this.queryOffsets.set( renderContext.id, baseOffset );
  48181. return baseOffset;
  48182. }
  48183. /**
  48184. * Asynchronously resolves all pending queries and returns the total duration.
  48185. * If there's already a pending resolve operation, returns that promise instead.
  48186. *
  48187. * @async
  48188. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  48189. */
  48190. async resolveQueriesAsync() {
  48191. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  48192. return this.lastValue;
  48193. }
  48194. if ( this.pendingResolve ) {
  48195. return this.pendingResolve;
  48196. }
  48197. this.pendingResolve = this._resolveQueries();
  48198. try {
  48199. const result = await this.pendingResolve;
  48200. return result;
  48201. } finally {
  48202. this.pendingResolve = null;
  48203. }
  48204. }
  48205. /**
  48206. * Internal method to resolve queries and calculate total duration.
  48207. *
  48208. * @async
  48209. * @private
  48210. * @returns {Promise<number>} The total duration in milliseconds.
  48211. */
  48212. async _resolveQueries() {
  48213. if ( this.isDisposed ) {
  48214. return this.lastValue;
  48215. }
  48216. try {
  48217. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  48218. return this.lastValue;
  48219. }
  48220. const currentOffsets = new Map( this.queryOffsets );
  48221. const queryCount = this.currentQueryIndex;
  48222. const bytesUsed = queryCount * 8;
  48223. // Reset state before GPU work
  48224. this.currentQueryIndex = 0;
  48225. this.queryOffsets.clear();
  48226. const commandEncoder = this.device.createCommandEncoder();
  48227. commandEncoder.resolveQuerySet(
  48228. this.querySet,
  48229. 0,
  48230. queryCount,
  48231. this.resolveBuffer,
  48232. 0
  48233. );
  48234. commandEncoder.copyBufferToBuffer(
  48235. this.resolveBuffer,
  48236. 0,
  48237. this.resultBuffer,
  48238. 0,
  48239. bytesUsed
  48240. );
  48241. const commandBuffer = commandEncoder.finish();
  48242. this.device.queue.submit( [ commandBuffer ] );
  48243. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  48244. return this.lastValue;
  48245. }
  48246. // Create and track the mapping operation
  48247. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  48248. if ( this.isDisposed ) {
  48249. if ( this.resultBuffer.mapState === 'mapped' ) {
  48250. this.resultBuffer.unmap();
  48251. }
  48252. return this.lastValue;
  48253. }
  48254. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  48255. let totalDuration = 0;
  48256. for ( const [ , baseOffset ] of currentOffsets ) {
  48257. const startTime = times[ baseOffset ];
  48258. const endTime = times[ baseOffset + 1 ];
  48259. const duration = Number( endTime - startTime ) / 1e6;
  48260. totalDuration += duration;
  48261. }
  48262. this.resultBuffer.unmap();
  48263. this.lastValue = totalDuration;
  48264. return totalDuration;
  48265. } catch ( error ) {
  48266. console.error( 'Error resolving queries:', error );
  48267. if ( this.resultBuffer.mapState === 'mapped' ) {
  48268. this.resultBuffer.unmap();
  48269. }
  48270. return this.lastValue;
  48271. }
  48272. }
  48273. /**
  48274. * Dispose of the query pool.
  48275. *
  48276. * @async
  48277. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  48278. */
  48279. async dispose() {
  48280. if ( this.isDisposed ) {
  48281. return;
  48282. }
  48283. this.isDisposed = true;
  48284. // Wait for pending resolve operation
  48285. if ( this.pendingResolve ) {
  48286. try {
  48287. await this.pendingResolve;
  48288. } catch ( error ) {
  48289. console.error( 'Error waiting for pending resolve:', error );
  48290. }
  48291. }
  48292. // Ensure buffer is unmapped before destroying
  48293. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  48294. try {
  48295. this.resultBuffer.unmap();
  48296. } catch ( error ) {
  48297. console.error( 'Error unmapping buffer:', error );
  48298. }
  48299. }
  48300. // Destroy resources
  48301. if ( this.querySet ) {
  48302. this.querySet.destroy();
  48303. this.querySet = null;
  48304. }
  48305. if ( this.resolveBuffer ) {
  48306. this.resolveBuffer.destroy();
  48307. this.resolveBuffer = null;
  48308. }
  48309. if ( this.resultBuffer ) {
  48310. this.resultBuffer.destroy();
  48311. this.resultBuffer = null;
  48312. }
  48313. this.queryOffsets.clear();
  48314. this.pendingResolve = null;
  48315. }
  48316. }
  48317. /*// debugger tools
  48318. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  48319. //*/
  48320. /**
  48321. * A backend implementation targeting WebGPU.
  48322. *
  48323. * @private
  48324. * @augments Backend
  48325. */
  48326. class WebGPUBackend extends Backend {
  48327. /**
  48328. * WebGPUBackend options.
  48329. *
  48330. * @typedef {Object} WebGPUBackend~Options
  48331. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  48332. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  48333. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  48334. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  48335. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  48336. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  48337. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  48338. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  48339. * @property {string} [powerPreference=undefined] - The power preference.
  48340. * @property {Object} [requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  48341. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  48342. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  48343. */
  48344. /**
  48345. * Constructs a new WebGPU backend.
  48346. *
  48347. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  48348. */
  48349. constructor( parameters = {} ) {
  48350. super( parameters );
  48351. /**
  48352. * This flag can be used for type testing.
  48353. *
  48354. * @type {boolean}
  48355. * @readonly
  48356. * @default true
  48357. */
  48358. this.isWebGPUBackend = true;
  48359. // some parameters require default values other than "undefined"
  48360. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  48361. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  48362. /**
  48363. * A reference to the device.
  48364. *
  48365. * @type {?GPUDevice}
  48366. * @default null
  48367. */
  48368. this.device = null;
  48369. /**
  48370. * A reference to the context.
  48371. *
  48372. * @type {?GPUCanvasContext}
  48373. * @default null
  48374. */
  48375. this.context = null;
  48376. /**
  48377. * A reference to the color attachment of the default framebuffer.
  48378. *
  48379. * @type {?GPUTexture}
  48380. * @default null
  48381. */
  48382. this.colorBuffer = null;
  48383. /**
  48384. * A reference to the default render pass descriptor.
  48385. *
  48386. * @type {?Object}
  48387. * @default null
  48388. */
  48389. this.defaultRenderPassdescriptor = null;
  48390. /**
  48391. * A reference to a backend module holding common utility functions.
  48392. *
  48393. * @type {WebGPUUtils}
  48394. */
  48395. this.utils = new WebGPUUtils( this );
  48396. /**
  48397. * A reference to a backend module holding shader attribute-related
  48398. * utility functions.
  48399. *
  48400. * @type {WebGPUAttributeUtils}
  48401. */
  48402. this.attributeUtils = new WebGPUAttributeUtils( this );
  48403. /**
  48404. * A reference to a backend module holding shader binding-related
  48405. * utility functions.
  48406. *
  48407. * @type {WebGPUBindingUtils}
  48408. */
  48409. this.bindingUtils = new WebGPUBindingUtils( this );
  48410. /**
  48411. * A reference to a backend module holding shader pipeline-related
  48412. * utility functions.
  48413. *
  48414. * @type {WebGPUPipelineUtils}
  48415. */
  48416. this.pipelineUtils = new WebGPUPipelineUtils( this );
  48417. /**
  48418. * A reference to a backend module holding shader texture-related
  48419. * utility functions.
  48420. *
  48421. * @type {WebGPUTextureUtils}
  48422. */
  48423. this.textureUtils = new WebGPUTextureUtils( this );
  48424. /**
  48425. * A map that manages the resolve buffers for occlusion queries.
  48426. *
  48427. * @type {Map<number,GPUBuffer>}
  48428. */
  48429. this.occludedResolveCache = new Map();
  48430. }
  48431. /**
  48432. * Initializes the backend so it is ready for usage.
  48433. *
  48434. * @async
  48435. * @param {Renderer} renderer - The renderer.
  48436. * @return {Promise} A Promise that resolves when the backend has been initialized.
  48437. */
  48438. async init( renderer ) {
  48439. await super.init( renderer );
  48440. //
  48441. const parameters = this.parameters;
  48442. // create the device if it is not passed with parameters
  48443. let device;
  48444. if ( parameters.device === undefined ) {
  48445. const adapterOptions = {
  48446. powerPreference: parameters.powerPreference
  48447. };
  48448. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  48449. if ( adapter === null ) {
  48450. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  48451. }
  48452. // feature support
  48453. const features = Object.values( GPUFeatureName );
  48454. const supportedFeatures = [];
  48455. for ( const name of features ) {
  48456. if ( adapter.features.has( name ) ) {
  48457. supportedFeatures.push( name );
  48458. }
  48459. }
  48460. const deviceDescriptor = {
  48461. requiredFeatures: supportedFeatures,
  48462. requiredLimits: parameters.requiredLimits
  48463. };
  48464. device = await adapter.requestDevice( deviceDescriptor );
  48465. } else {
  48466. device = parameters.device;
  48467. }
  48468. device.lost.then( ( info ) => {
  48469. const deviceLossInfo = {
  48470. api: 'WebGPU',
  48471. message: info.message || 'Unknown reason',
  48472. reason: info.reason || null,
  48473. originalEvent: info
  48474. };
  48475. renderer.onDeviceLost( deviceLossInfo );
  48476. } );
  48477. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  48478. this.device = device;
  48479. this.context = context;
  48480. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  48481. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  48482. this.context.configure( {
  48483. device: this.device,
  48484. format: this.utils.getPreferredCanvasFormat(),
  48485. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  48486. alphaMode: alphaMode
  48487. } );
  48488. this.updateSize();
  48489. }
  48490. /**
  48491. * The coordinate system of the backend.
  48492. *
  48493. * @type {number}
  48494. * @readonly
  48495. */
  48496. get coordinateSystem() {
  48497. return WebGPUCoordinateSystem;
  48498. }
  48499. /**
  48500. * This method performs a readback operation by moving buffer data from
  48501. * a storage buffer attribute from the GPU to the CPU.
  48502. *
  48503. * @async
  48504. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48505. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48506. */
  48507. async getArrayBufferAsync( attribute ) {
  48508. return await this.attributeUtils.getArrayBufferAsync( attribute );
  48509. }
  48510. /**
  48511. * Returns the backend's rendering context.
  48512. *
  48513. * @return {GPUCanvasContext} The rendering context.
  48514. */
  48515. getContext() {
  48516. return this.context;
  48517. }
  48518. /**
  48519. * Returns the default render pass descriptor.
  48520. *
  48521. * In WebGPU, the default framebuffer must be configured
  48522. * like custom framebuffers so the backend needs a render
  48523. * pass descriptor even when rendering directly to screen.
  48524. *
  48525. * @private
  48526. * @return {Object} The render pass descriptor.
  48527. */
  48528. _getDefaultRenderPassDescriptor() {
  48529. let descriptor = this.defaultRenderPassdescriptor;
  48530. if ( descriptor === null ) {
  48531. const renderer = this.renderer;
  48532. descriptor = {
  48533. colorAttachments: [ {
  48534. view: null
  48535. } ],
  48536. };
  48537. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  48538. descriptor.depthStencilAttachment = {
  48539. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  48540. };
  48541. }
  48542. const colorAttachment = descriptor.colorAttachments[ 0 ];
  48543. if ( this.renderer.samples > 0 ) {
  48544. colorAttachment.view = this.colorBuffer.createView();
  48545. } else {
  48546. colorAttachment.resolveTarget = undefined;
  48547. }
  48548. this.defaultRenderPassdescriptor = descriptor;
  48549. }
  48550. const colorAttachment = descriptor.colorAttachments[ 0 ];
  48551. if ( this.renderer.samples > 0 ) {
  48552. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  48553. } else {
  48554. colorAttachment.view = this.context.getCurrentTexture().createView();
  48555. }
  48556. return descriptor;
  48557. }
  48558. /**
  48559. * Returns the render pass descriptor for the given render context.
  48560. *
  48561. * @private
  48562. * @param {RenderContext} renderContext - The render context.
  48563. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  48564. * @return {Object} The render pass descriptor.
  48565. */
  48566. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  48567. const renderTarget = renderContext.renderTarget;
  48568. const renderTargetData = this.get( renderTarget );
  48569. let descriptors = renderTargetData.descriptors;
  48570. if ( descriptors === undefined ||
  48571. renderTargetData.width !== renderTarget.width ||
  48572. renderTargetData.height !== renderTarget.height ||
  48573. renderTargetData.dimensions !== renderTarget.dimensions ||
  48574. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  48575. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  48576. renderTargetData.samples !== renderTarget.samples
  48577. ) {
  48578. descriptors = {};
  48579. renderTargetData.descriptors = descriptors;
  48580. // dispose
  48581. const onDispose = () => {
  48582. renderTarget.removeEventListener( 'dispose', onDispose );
  48583. this.delete( renderTarget );
  48584. };
  48585. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  48586. renderTarget.addEventListener( 'dispose', onDispose );
  48587. }
  48588. }
  48589. const cacheKey = renderContext.getCacheKey();
  48590. let descriptorBase = descriptors[ cacheKey ];
  48591. if ( descriptorBase === undefined ) {
  48592. const textures = renderContext.textures;
  48593. const textureViews = [];
  48594. let sliceIndex;
  48595. for ( let i = 0; i < textures.length; i ++ ) {
  48596. const textureData = this.get( textures[ i ] );
  48597. const viewDescriptor = {
  48598. label: `colorAttachment_${ i }`,
  48599. baseMipLevel: renderContext.activeMipmapLevel,
  48600. mipLevelCount: 1,
  48601. baseArrayLayer: renderContext.activeCubeFace,
  48602. arrayLayerCount: 1,
  48603. dimension: GPUTextureViewDimension.TwoD
  48604. };
  48605. if ( renderTarget.isRenderTarget3D ) {
  48606. sliceIndex = renderContext.activeCubeFace;
  48607. viewDescriptor.baseArrayLayer = 0;
  48608. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  48609. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  48610. } else if ( renderTarget.isRenderTargetArray ) {
  48611. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  48612. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  48613. }
  48614. const textureView = textureData.texture.createView( viewDescriptor );
  48615. let view, resolveTarget;
  48616. if ( textureData.msaaTexture !== undefined ) {
  48617. view = textureData.msaaTexture.createView();
  48618. resolveTarget = textureView;
  48619. } else {
  48620. view = textureView;
  48621. resolveTarget = undefined;
  48622. }
  48623. textureViews.push( {
  48624. view,
  48625. resolveTarget,
  48626. depthSlice: sliceIndex
  48627. } );
  48628. }
  48629. descriptorBase = { textureViews };
  48630. if ( renderContext.depth ) {
  48631. const depthTextureData = this.get( renderContext.depthTexture );
  48632. descriptorBase.depthStencilView = depthTextureData.texture.createView();
  48633. }
  48634. descriptors[ cacheKey ] = descriptorBase;
  48635. renderTargetData.width = renderTarget.width;
  48636. renderTargetData.height = renderTarget.height;
  48637. renderTargetData.samples = renderTarget.samples;
  48638. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  48639. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  48640. renderTargetData.dimensions = renderTarget.dimensions;
  48641. }
  48642. const descriptor = {
  48643. colorAttachments: []
  48644. };
  48645. // Apply dynamic properties to cached views
  48646. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  48647. const viewInfo = descriptorBase.textureViews[ i ];
  48648. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  48649. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  48650. clearValue = colorAttachmentsConfig.clearValue;
  48651. }
  48652. descriptor.colorAttachments.push( {
  48653. view: viewInfo.view,
  48654. depthSlice: viewInfo.depthSlice,
  48655. resolveTarget: viewInfo.resolveTarget,
  48656. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  48657. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  48658. clearValue: clearValue
  48659. } );
  48660. }
  48661. if ( descriptorBase.depthStencilView ) {
  48662. descriptor.depthStencilAttachment = {
  48663. view: descriptorBase.depthStencilView
  48664. };
  48665. }
  48666. return descriptor;
  48667. }
  48668. /**
  48669. * This method is executed at the beginning of a render call and prepares
  48670. * the WebGPU state for upcoming render calls
  48671. *
  48672. * @param {RenderContext} renderContext - The render context.
  48673. */
  48674. beginRender( renderContext ) {
  48675. const renderContextData = this.get( renderContext );
  48676. const device = this.device;
  48677. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48678. let occlusionQuerySet;
  48679. if ( occlusionQueryCount > 0 ) {
  48680. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  48681. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  48682. // Get a reference to the array of objects with queries. The renderContextData property
  48683. // can be changed by another render pass before the buffer.mapAsyc() completes.
  48684. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  48685. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  48686. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  48687. //
  48688. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  48689. renderContextData.occlusionQuerySet = occlusionQuerySet;
  48690. renderContextData.occlusionQueryIndex = 0;
  48691. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  48692. renderContextData.lastOcclusionObject = null;
  48693. }
  48694. let descriptor;
  48695. if ( renderContext.textures === null ) {
  48696. descriptor = this._getDefaultRenderPassDescriptor();
  48697. } else {
  48698. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  48699. }
  48700. this.initTimestampQuery( renderContext, descriptor );
  48701. descriptor.occlusionQuerySet = occlusionQuerySet;
  48702. const depthStencilAttachment = descriptor.depthStencilAttachment;
  48703. if ( renderContext.textures !== null ) {
  48704. const colorAttachments = descriptor.colorAttachments;
  48705. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  48706. const colorAttachment = colorAttachments[ i ];
  48707. if ( renderContext.clearColor ) {
  48708. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  48709. colorAttachment.loadOp = GPULoadOp.Clear;
  48710. colorAttachment.storeOp = GPUStoreOp.Store;
  48711. } else {
  48712. colorAttachment.loadOp = GPULoadOp.Load;
  48713. colorAttachment.storeOp = GPUStoreOp.Store;
  48714. }
  48715. }
  48716. } else {
  48717. const colorAttachment = descriptor.colorAttachments[ 0 ];
  48718. if ( renderContext.clearColor ) {
  48719. colorAttachment.clearValue = renderContext.clearColorValue;
  48720. colorAttachment.loadOp = GPULoadOp.Clear;
  48721. colorAttachment.storeOp = GPUStoreOp.Store;
  48722. } else {
  48723. colorAttachment.loadOp = GPULoadOp.Load;
  48724. colorAttachment.storeOp = GPUStoreOp.Store;
  48725. }
  48726. }
  48727. //
  48728. if ( renderContext.depth ) {
  48729. if ( renderContext.clearDepth ) {
  48730. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  48731. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  48732. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48733. } else {
  48734. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48735. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48736. }
  48737. }
  48738. if ( renderContext.stencil ) {
  48739. if ( renderContext.clearStencil ) {
  48740. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  48741. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  48742. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48743. } else {
  48744. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48745. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48746. }
  48747. }
  48748. //
  48749. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  48750. const currentPass = encoder.beginRenderPass( descriptor );
  48751. //
  48752. renderContextData.descriptor = descriptor;
  48753. renderContextData.encoder = encoder;
  48754. renderContextData.currentPass = currentPass;
  48755. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  48756. renderContextData.renderBundles = [];
  48757. //
  48758. if ( renderContext.viewport ) {
  48759. this.updateViewport( renderContext );
  48760. }
  48761. if ( renderContext.scissor ) {
  48762. const { x, y, width, height } = renderContext.scissorValue;
  48763. currentPass.setScissorRect( x, y, width, height );
  48764. }
  48765. }
  48766. /**
  48767. * This method is executed at the end of a render call and finalizes work
  48768. * after draw calls.
  48769. *
  48770. * @param {RenderContext} renderContext - The render context.
  48771. */
  48772. finishRender( renderContext ) {
  48773. const renderContextData = this.get( renderContext );
  48774. const occlusionQueryCount = renderContext.occlusionQueryCount;
  48775. if ( renderContextData.renderBundles.length > 0 ) {
  48776. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  48777. }
  48778. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  48779. renderContextData.currentPass.endOcclusionQuery();
  48780. }
  48781. renderContextData.currentPass.end();
  48782. if ( occlusionQueryCount > 0 ) {
  48783. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  48784. //
  48785. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  48786. if ( queryResolveBuffer === undefined ) {
  48787. queryResolveBuffer = this.device.createBuffer(
  48788. {
  48789. size: bufferSize,
  48790. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  48791. }
  48792. );
  48793. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  48794. }
  48795. //
  48796. const readBuffer = this.device.createBuffer(
  48797. {
  48798. size: bufferSize,
  48799. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48800. }
  48801. );
  48802. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  48803. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  48804. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  48805. renderContextData.occlusionQueryBuffer = readBuffer;
  48806. //
  48807. this.resolveOccludedAsync( renderContext );
  48808. }
  48809. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  48810. //
  48811. if ( renderContext.textures !== null ) {
  48812. const textures = renderContext.textures;
  48813. for ( let i = 0; i < textures.length; i ++ ) {
  48814. const texture = textures[ i ];
  48815. if ( texture.generateMipmaps === true ) {
  48816. this.textureUtils.generateMipmaps( texture );
  48817. }
  48818. }
  48819. }
  48820. }
  48821. /**
  48822. * Returns `true` if the given 3D object is fully occluded by other
  48823. * 3D objects in the scene.
  48824. *
  48825. * @param {RenderContext} renderContext - The render context.
  48826. * @param {Object3D} object - The 3D object to test.
  48827. * @return {boolean} Whether the 3D object is fully occluded or not.
  48828. */
  48829. isOccluded( renderContext, object ) {
  48830. const renderContextData = this.get( renderContext );
  48831. return renderContextData.occluded && renderContextData.occluded.has( object );
  48832. }
  48833. /**
  48834. * This method processes the result of occlusion queries and writes it
  48835. * into render context data.
  48836. *
  48837. * @async
  48838. * @param {RenderContext} renderContext - The render context.
  48839. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  48840. */
  48841. async resolveOccludedAsync( renderContext ) {
  48842. const renderContextData = this.get( renderContext );
  48843. // handle occlusion query results
  48844. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  48845. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  48846. const occluded = new WeakSet();
  48847. renderContextData.currentOcclusionQueryObjects = null;
  48848. renderContextData.currentOcclusionQueryBuffer = null;
  48849. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  48850. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  48851. const results = new BigUint64Array( buffer );
  48852. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  48853. if ( results[ i ] === BigInt( 0 ) ) {
  48854. occluded.add( currentOcclusionQueryObjects[ i ] );
  48855. }
  48856. }
  48857. currentOcclusionQueryBuffer.destroy();
  48858. renderContextData.occluded = occluded;
  48859. }
  48860. }
  48861. /**
  48862. * Updates the viewport with the values from the given render context.
  48863. *
  48864. * @param {RenderContext} renderContext - The render context.
  48865. */
  48866. updateViewport( renderContext ) {
  48867. const { currentPass } = this.get( renderContext );
  48868. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  48869. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  48870. }
  48871. /**
  48872. * Returns the clear color and alpha into a single
  48873. * color object.
  48874. *
  48875. * @return {Color4} The clear color.
  48876. */
  48877. getClearColor() {
  48878. const clearColor = super.getClearColor();
  48879. // only premultiply alpha when alphaMode is "premultiplied"
  48880. if ( this.renderer.alpha === true ) {
  48881. clearColor.r *= clearColor.a;
  48882. clearColor.g *= clearColor.a;
  48883. clearColor.b *= clearColor.a;
  48884. }
  48885. return clearColor;
  48886. }
  48887. /**
  48888. * Performs a clear operation.
  48889. *
  48890. * @param {boolean} color - Whether the color buffer should be cleared or not.
  48891. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  48892. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  48893. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  48894. */
  48895. clear( color, depth, stencil, renderTargetContext = null ) {
  48896. const device = this.device;
  48897. const renderer = this.renderer;
  48898. let colorAttachments = [];
  48899. let depthStencilAttachment;
  48900. let clearValue;
  48901. let supportsDepth;
  48902. let supportsStencil;
  48903. if ( color ) {
  48904. const clearColor = this.getClearColor();
  48905. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  48906. }
  48907. if ( renderTargetContext === null ) {
  48908. supportsDepth = renderer.depth;
  48909. supportsStencil = renderer.stencil;
  48910. const descriptor = this._getDefaultRenderPassDescriptor();
  48911. if ( color ) {
  48912. colorAttachments = descriptor.colorAttachments;
  48913. const colorAttachment = colorAttachments[ 0 ];
  48914. colorAttachment.clearValue = clearValue;
  48915. colorAttachment.loadOp = GPULoadOp.Clear;
  48916. colorAttachment.storeOp = GPUStoreOp.Store;
  48917. }
  48918. if ( supportsDepth || supportsStencil ) {
  48919. depthStencilAttachment = descriptor.depthStencilAttachment;
  48920. }
  48921. } else {
  48922. supportsDepth = renderTargetContext.depth;
  48923. supportsStencil = renderTargetContext.stencil;
  48924. const clearConfig = {
  48925. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  48926. clearValue: color ? clearValue : undefined
  48927. };
  48928. if ( supportsDepth ) {
  48929. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  48930. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  48931. clearConfig.depthStoreOp = GPUStoreOp.Store;
  48932. }
  48933. if ( supportsStencil ) {
  48934. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  48935. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  48936. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  48937. }
  48938. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  48939. colorAttachments = descriptor.colorAttachments;
  48940. depthStencilAttachment = descriptor.depthStencilAttachment;
  48941. }
  48942. if ( supportsDepth && depthStencilAttachment && depthStencilAttachment.depthLoadOp === undefined ) {
  48943. if ( depth ) {
  48944. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  48945. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  48946. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48947. } else {
  48948. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  48949. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  48950. }
  48951. }
  48952. //
  48953. if ( supportsStencil && depthStencilAttachment && depthStencilAttachment.stencilLoadOp === undefined ) {
  48954. if ( stencil ) {
  48955. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  48956. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  48957. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48958. } else {
  48959. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  48960. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  48961. }
  48962. }
  48963. //
  48964. const encoder = device.createCommandEncoder( { label: 'clear' } );
  48965. const currentPass = encoder.beginRenderPass( {
  48966. colorAttachments,
  48967. depthStencilAttachment
  48968. } );
  48969. currentPass.end();
  48970. device.queue.submit( [ encoder.finish() ] );
  48971. }
  48972. // compute
  48973. /**
  48974. * This method is executed at the beginning of a compute call and
  48975. * prepares the state for upcoming compute tasks.
  48976. *
  48977. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  48978. */
  48979. beginCompute( computeGroup ) {
  48980. const groupGPU = this.get( computeGroup );
  48981. const descriptor = {
  48982. label: 'computeGroup_' + computeGroup.id
  48983. };
  48984. this.initTimestampQuery( computeGroup, descriptor );
  48985. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  48986. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  48987. }
  48988. /**
  48989. * Executes a compute command for the given compute node.
  48990. *
  48991. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  48992. * @param {Node} computeNode - The compute node.
  48993. * @param {Array<BindGroup>} bindings - The bindings.
  48994. * @param {ComputePipeline} pipeline - The compute pipeline.
  48995. */
  48996. compute( computeGroup, computeNode, bindings, pipeline ) {
  48997. const { passEncoderGPU } = this.get( computeGroup );
  48998. // pipeline
  48999. const pipelineGPU = this.get( pipeline ).pipeline;
  49000. passEncoderGPU.setPipeline( pipelineGPU );
  49001. // bind groups
  49002. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  49003. const bindGroup = bindings[ i ];
  49004. const bindingsData = this.get( bindGroup );
  49005. passEncoderGPU.setBindGroup( i, bindingsData.group );
  49006. }
  49007. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  49008. const computeNodeData = this.get( computeNode );
  49009. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  49010. const { dispatchSize } = computeNodeData;
  49011. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  49012. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  49013. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  49014. } else {
  49015. dispatchSize.x = computeNode.dispatchCount;
  49016. }
  49017. passEncoderGPU.dispatchWorkgroups(
  49018. dispatchSize.x,
  49019. dispatchSize.y,
  49020. dispatchSize.z
  49021. );
  49022. }
  49023. /**
  49024. * This method is executed at the end of a compute call and
  49025. * finalizes work after compute tasks.
  49026. *
  49027. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  49028. */
  49029. finishCompute( computeGroup ) {
  49030. const groupData = this.get( computeGroup );
  49031. groupData.passEncoderGPU.end();
  49032. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  49033. }
  49034. /**
  49035. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  49036. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  49037. *
  49038. * @async
  49039. * @return {Promise} A Promise that resolves when synchronization has been finished.
  49040. */
  49041. async waitForGPU() {
  49042. await this.device.queue.onSubmittedWorkDone();
  49043. }
  49044. // render object
  49045. /**
  49046. * Executes a draw command for the given render object.
  49047. *
  49048. * @param {RenderObject} renderObject - The render object to draw.
  49049. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  49050. */
  49051. draw( renderObject, info ) {
  49052. const { object, material, context, pipeline } = renderObject;
  49053. const bindings = renderObject.getBindings();
  49054. const renderContextData = this.get( context );
  49055. const pipelineGPU = this.get( pipeline ).pipeline;
  49056. const currentSets = renderContextData.currentSets;
  49057. const passEncoderGPU = renderContextData.currentPass;
  49058. const drawParams = renderObject.getDrawParameters();
  49059. if ( drawParams === null ) return;
  49060. // pipeline
  49061. if ( currentSets.pipeline !== pipelineGPU ) {
  49062. passEncoderGPU.setPipeline( pipelineGPU );
  49063. currentSets.pipeline = pipelineGPU;
  49064. }
  49065. // bind groups
  49066. const currentBindingGroups = currentSets.bindingGroups;
  49067. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  49068. const bindGroup = bindings[ i ];
  49069. const bindingsData = this.get( bindGroup );
  49070. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  49071. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  49072. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  49073. }
  49074. }
  49075. // attributes
  49076. const index = renderObject.getIndex();
  49077. const hasIndex = ( index !== null );
  49078. // index
  49079. if ( hasIndex === true ) {
  49080. if ( currentSets.index !== index ) {
  49081. const buffer = this.get( index ).buffer;
  49082. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  49083. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  49084. currentSets.index = index;
  49085. }
  49086. }
  49087. // vertex buffers
  49088. const vertexBuffers = renderObject.getVertexBuffers();
  49089. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  49090. const vertexBuffer = vertexBuffers[ i ];
  49091. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  49092. const buffer = this.get( vertexBuffer ).buffer;
  49093. passEncoderGPU.setVertexBuffer( i, buffer );
  49094. currentSets.attributes[ i ] = vertexBuffer;
  49095. }
  49096. }
  49097. // occlusion queries - handle multiple consecutive draw calls for an object
  49098. if ( renderContextData.occlusionQuerySet !== undefined ) {
  49099. const lastObject = renderContextData.lastOcclusionObject;
  49100. if ( lastObject !== object ) {
  49101. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  49102. passEncoderGPU.endOcclusionQuery();
  49103. renderContextData.occlusionQueryIndex ++;
  49104. }
  49105. if ( object.occlusionTest === true ) {
  49106. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  49107. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  49108. }
  49109. renderContextData.lastOcclusionObject = object;
  49110. }
  49111. }
  49112. // stencil
  49113. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  49114. passEncoderGPU.setStencilReference( material.stencilRef );
  49115. renderContextData.currentStencilRef = material.stencilRef;
  49116. }
  49117. // draw
  49118. const draw = () => {
  49119. if ( object.isBatchedMesh === true ) {
  49120. const starts = object._multiDrawStarts;
  49121. const counts = object._multiDrawCounts;
  49122. const drawCount = object._multiDrawCount;
  49123. const drawInstances = object._multiDrawInstances;
  49124. if ( drawInstances !== null ) {
  49125. // @deprecated, r174
  49126. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  49127. }
  49128. for ( let i = 0; i < drawCount; i ++ ) {
  49129. const count = drawInstances ? drawInstances[ i ] : 1;
  49130. const firstInstance = count > 1 ? 0 : i;
  49131. if ( hasIndex === true ) {
  49132. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  49133. } else {
  49134. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  49135. }
  49136. info.update( object, counts[ i ], count );
  49137. }
  49138. } else if ( hasIndex === true ) {
  49139. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  49140. const indirect = renderObject.getIndirect();
  49141. if ( indirect !== null ) {
  49142. const buffer = this.get( indirect ).buffer;
  49143. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  49144. } else {
  49145. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  49146. }
  49147. info.update( object, indexCount, instanceCount );
  49148. } else {
  49149. const { vertexCount, instanceCount, firstVertex } = drawParams;
  49150. const indirect = renderObject.getIndirect();
  49151. if ( indirect !== null ) {
  49152. const buffer = this.get( indirect ).buffer;
  49153. passEncoderGPU.drawIndirect( buffer, 0 );
  49154. } else {
  49155. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  49156. }
  49157. info.update( object, vertexCount, instanceCount );
  49158. }
  49159. };
  49160. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  49161. const cameraData = this.get( renderObject.camera );
  49162. const cameras = renderObject.camera.cameras;
  49163. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  49164. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  49165. const bindingsData = this.get( cameraIndex );
  49166. const indexesGPU = [];
  49167. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  49168. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49169. data[ 0 ] = i;
  49170. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  49171. indexesGPU.push( bindGroupIndex );
  49172. }
  49173. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  49174. }
  49175. const pixelRatio = this.renderer.getPixelRatio();
  49176. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  49177. const subCamera = cameras[ i ];
  49178. if ( object.layers.test( subCamera.layers ) ) {
  49179. const vp = subCamera.viewport;
  49180. passEncoderGPU.setViewport(
  49181. Math.floor( vp.x * pixelRatio ),
  49182. Math.floor( vp.y * pixelRatio ),
  49183. Math.floor( vp.width * pixelRatio ),
  49184. Math.floor( vp.height * pixelRatio ),
  49185. context.viewportValue.minDepth,
  49186. context.viewportValue.maxDepth
  49187. );
  49188. passEncoderGPU.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  49189. draw();
  49190. }
  49191. }
  49192. } else {
  49193. draw();
  49194. }
  49195. }
  49196. // cache key
  49197. /**
  49198. * Returns `true` if the render pipeline requires an update.
  49199. *
  49200. * @param {RenderObject} renderObject - The render object.
  49201. * @return {boolean} Whether the render pipeline requires an update or not.
  49202. */
  49203. needsRenderUpdate( renderObject ) {
  49204. const data = this.get( renderObject );
  49205. const { object, material } = renderObject;
  49206. const utils = this.utils;
  49207. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  49208. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  49209. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  49210. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  49211. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  49212. let needsUpdate = false;
  49213. if ( data.material !== material || data.materialVersion !== material.version ||
  49214. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  49215. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  49216. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  49217. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  49218. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  49219. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  49220. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  49221. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  49222. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  49223. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  49224. data.primitiveTopology !== primitiveTopology ||
  49225. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  49226. ) {
  49227. data.material = material; data.materialVersion = material.version;
  49228. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  49229. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  49230. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  49231. data.colorWrite = material.colorWrite;
  49232. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  49233. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  49234. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  49235. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  49236. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  49237. data.sampleCount = sampleCount;
  49238. data.colorSpace = colorSpace;
  49239. data.colorFormat = colorFormat;
  49240. data.depthStencilFormat = depthStencilFormat;
  49241. data.primitiveTopology = primitiveTopology;
  49242. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  49243. needsUpdate = true;
  49244. }
  49245. return needsUpdate;
  49246. }
  49247. /**
  49248. * Returns a cache key that is used to identify render pipelines.
  49249. *
  49250. * @param {RenderObject} renderObject - The render object.
  49251. * @return {string} The cache key.
  49252. */
  49253. getRenderCacheKey( renderObject ) {
  49254. const { object, material } = renderObject;
  49255. const utils = this.utils;
  49256. const renderContext = renderObject.context;
  49257. return [
  49258. material.transparent, material.blending, material.premultipliedAlpha,
  49259. material.blendSrc, material.blendDst, material.blendEquation,
  49260. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  49261. material.colorWrite,
  49262. material.depthWrite, material.depthTest, material.depthFunc,
  49263. material.stencilWrite, material.stencilFunc,
  49264. material.stencilFail, material.stencilZFail, material.stencilZPass,
  49265. material.stencilFuncMask, material.stencilWriteMask,
  49266. material.side,
  49267. utils.getSampleCountRenderContext( renderContext ),
  49268. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  49269. utils.getPrimitiveTopology( object, material ),
  49270. renderObject.getGeometryCacheKey(),
  49271. renderObject.clippingContextCacheKey
  49272. ].join();
  49273. }
  49274. // textures
  49275. /**
  49276. * Creates a GPU sampler for the given texture.
  49277. *
  49278. * @param {Texture} texture - The texture to create the sampler for.
  49279. */
  49280. createSampler( texture ) {
  49281. this.textureUtils.createSampler( texture );
  49282. }
  49283. /**
  49284. * Destroys the GPU sampler for the given texture.
  49285. *
  49286. * @param {Texture} texture - The texture to destroy the sampler for.
  49287. */
  49288. destroySampler( texture ) {
  49289. this.textureUtils.destroySampler( texture );
  49290. }
  49291. /**
  49292. * Creates a default texture for the given texture that can be used
  49293. * as a placeholder until the actual texture is ready for usage.
  49294. *
  49295. * @param {Texture} texture - The texture to create a default texture for.
  49296. */
  49297. createDefaultTexture( texture ) {
  49298. this.textureUtils.createDefaultTexture( texture );
  49299. }
  49300. /**
  49301. * Defines a texture on the GPU for the given texture object.
  49302. *
  49303. * @param {Texture} texture - The texture.
  49304. * @param {Object} [options={}] - Optional configuration parameter.
  49305. */
  49306. createTexture( texture, options ) {
  49307. this.textureUtils.createTexture( texture, options );
  49308. }
  49309. /**
  49310. * Uploads the updated texture data to the GPU.
  49311. *
  49312. * @param {Texture} texture - The texture.
  49313. * @param {Object} [options={}] - Optional configuration parameter.
  49314. */
  49315. updateTexture( texture, options ) {
  49316. this.textureUtils.updateTexture( texture, options );
  49317. }
  49318. /**
  49319. * Generates mipmaps for the given texture.
  49320. *
  49321. * @param {Texture} texture - The texture.
  49322. */
  49323. generateMipmaps( texture ) {
  49324. this.textureUtils.generateMipmaps( texture );
  49325. }
  49326. /**
  49327. * Destroys the GPU data for the given texture object.
  49328. *
  49329. * @param {Texture} texture - The texture.
  49330. */
  49331. destroyTexture( texture ) {
  49332. this.textureUtils.destroyTexture( texture );
  49333. }
  49334. /**
  49335. * Returns texture data as a typed array.
  49336. *
  49337. * @async
  49338. * @param {Texture} texture - The texture to copy.
  49339. * @param {number} x - The x coordinate of the copy origin.
  49340. * @param {number} y - The y coordinate of the copy origin.
  49341. * @param {number} width - The width of the copy.
  49342. * @param {number} height - The height of the copy.
  49343. * @param {number} faceIndex - The face index.
  49344. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  49345. */
  49346. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  49347. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  49348. }
  49349. /**
  49350. * Inits a time stamp query for the given render context.
  49351. *
  49352. * @param {RenderContext} renderContext - The render context.
  49353. * @param {Object} descriptor - The query descriptor.
  49354. */
  49355. initTimestampQuery( renderContext, descriptor ) {
  49356. if ( ! this.trackTimestamp ) return;
  49357. const type = renderContext.isComputeNode ? 'compute' : 'render';
  49358. if ( ! this.timestampQueryPool[ type ] ) {
  49359. // TODO: Variable maxQueries?
  49360. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  49361. }
  49362. const timestampQueryPool = this.timestampQueryPool[ type ];
  49363. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  49364. descriptor.timestampWrites = {
  49365. querySet: timestampQueryPool.querySet,
  49366. beginningOfPassWriteIndex: baseOffset,
  49367. endOfPassWriteIndex: baseOffset + 1,
  49368. };
  49369. }
  49370. // node builder
  49371. /**
  49372. * Returns a node builder for the given render object.
  49373. *
  49374. * @param {RenderObject} object - The render object.
  49375. * @param {Renderer} renderer - The renderer.
  49376. * @return {WGSLNodeBuilder} The node builder.
  49377. */
  49378. createNodeBuilder( object, renderer ) {
  49379. return new WGSLNodeBuilder( object, renderer );
  49380. }
  49381. // program
  49382. /**
  49383. * Creates a shader program from the given programmable stage.
  49384. *
  49385. * @param {ProgrammableStage} program - The programmable stage.
  49386. */
  49387. createProgram( program ) {
  49388. const programGPU = this.get( program );
  49389. programGPU.module = {
  49390. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  49391. entryPoint: 'main'
  49392. };
  49393. }
  49394. /**
  49395. * Destroys the shader program of the given programmable stage.
  49396. *
  49397. * @param {ProgrammableStage} program - The programmable stage.
  49398. */
  49399. destroyProgram( program ) {
  49400. this.delete( program );
  49401. }
  49402. // pipelines
  49403. /**
  49404. * Creates a render pipeline for the given render object.
  49405. *
  49406. * @param {RenderObject} renderObject - The render object.
  49407. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49408. */
  49409. createRenderPipeline( renderObject, promises ) {
  49410. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  49411. }
  49412. /**
  49413. * Creates a compute pipeline for the given compute node.
  49414. *
  49415. * @param {ComputePipeline} computePipeline - The compute pipeline.
  49416. * @param {Array<BindGroup>} bindings - The bindings.
  49417. */
  49418. createComputePipeline( computePipeline, bindings ) {
  49419. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  49420. }
  49421. /**
  49422. * Prepares the state for encoding render bundles.
  49423. *
  49424. * @param {RenderContext} renderContext - The render context.
  49425. */
  49426. beginBundle( renderContext ) {
  49427. const renderContextData = this.get( renderContext );
  49428. renderContextData._currentPass = renderContextData.currentPass;
  49429. renderContextData._currentSets = renderContextData.currentSets;
  49430. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  49431. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  49432. }
  49433. /**
  49434. * After processing render bundles this method finalizes related work.
  49435. *
  49436. * @param {RenderContext} renderContext - The render context.
  49437. * @param {RenderBundle} bundle - The render bundle.
  49438. */
  49439. finishBundle( renderContext, bundle ) {
  49440. const renderContextData = this.get( renderContext );
  49441. const bundleEncoder = renderContextData.currentPass;
  49442. const bundleGPU = bundleEncoder.finish();
  49443. this.get( bundle ).bundleGPU = bundleGPU;
  49444. // restore render pass state
  49445. renderContextData.currentSets = renderContextData._currentSets;
  49446. renderContextData.currentPass = renderContextData._currentPass;
  49447. }
  49448. /**
  49449. * Adds a render bundle to the render context data.
  49450. *
  49451. * @param {RenderContext} renderContext - The render context.
  49452. * @param {RenderBundle} bundle - The render bundle to add.
  49453. */
  49454. addBundle( renderContext, bundle ) {
  49455. const renderContextData = this.get( renderContext );
  49456. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  49457. }
  49458. // bindings
  49459. /**
  49460. * Creates bindings from the given bind group definition.
  49461. *
  49462. * @param {BindGroup} bindGroup - The bind group.
  49463. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49464. * @param {number} cacheIndex - The cache index.
  49465. * @param {number} version - The version.
  49466. */
  49467. createBindings( bindGroup, bindings, cacheIndex, version ) {
  49468. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  49469. }
  49470. /**
  49471. * Updates the given bind group definition.
  49472. *
  49473. * @param {BindGroup} bindGroup - The bind group.
  49474. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49475. * @param {number} cacheIndex - The cache index.
  49476. * @param {number} version - The version.
  49477. */
  49478. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  49479. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  49480. }
  49481. /**
  49482. * Updates a buffer binding.
  49483. *
  49484. * @param {Buffer} binding - The buffer binding to update.
  49485. */
  49486. updateBinding( binding ) {
  49487. this.bindingUtils.updateBinding( binding );
  49488. }
  49489. // attributes
  49490. /**
  49491. * Creates the buffer of an indexed shader attribute.
  49492. *
  49493. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  49494. */
  49495. createIndexAttribute( attribute ) {
  49496. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  49497. }
  49498. /**
  49499. * Creates the GPU buffer of a shader attribute.
  49500. *
  49501. * @param {BufferAttribute} attribute - The buffer attribute.
  49502. */
  49503. createAttribute( attribute ) {
  49504. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  49505. }
  49506. /**
  49507. * Creates the GPU buffer of a storage attribute.
  49508. *
  49509. * @param {BufferAttribute} attribute - The buffer attribute.
  49510. */
  49511. createStorageAttribute( attribute ) {
  49512. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  49513. }
  49514. /**
  49515. * Creates the GPU buffer of an indirect storage attribute.
  49516. *
  49517. * @param {BufferAttribute} attribute - The buffer attribute.
  49518. */
  49519. createIndirectStorageAttribute( attribute ) {
  49520. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  49521. }
  49522. /**
  49523. * Updates the GPU buffer of a shader attribute.
  49524. *
  49525. * @param {BufferAttribute} attribute - The buffer attribute to update.
  49526. */
  49527. updateAttribute( attribute ) {
  49528. this.attributeUtils.updateAttribute( attribute );
  49529. }
  49530. /**
  49531. * Destroys the GPU buffer of a shader attribute.
  49532. *
  49533. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  49534. */
  49535. destroyAttribute( attribute ) {
  49536. this.attributeUtils.destroyAttribute( attribute );
  49537. }
  49538. // canvas
  49539. /**
  49540. * Triggers an update of the default render pass descriptor.
  49541. */
  49542. updateSize() {
  49543. this.colorBuffer = this.textureUtils.getColorBuffer();
  49544. this.defaultRenderPassdescriptor = null;
  49545. }
  49546. // utils public
  49547. /**
  49548. * Returns the maximum anisotropy texture filtering value.
  49549. *
  49550. * @return {number} The maximum anisotropy texture filtering value.
  49551. */
  49552. getMaxAnisotropy() {
  49553. return 16;
  49554. }
  49555. /**
  49556. * Checks if the given feature is supported by the backend.
  49557. *
  49558. * @param {string} name - The feature's name.
  49559. * @return {boolean} Whether the feature is supported or not.
  49560. */
  49561. hasFeature( name ) {
  49562. return this.device.features.has( name );
  49563. }
  49564. /**
  49565. * Copies data of the given source texture to the given destination texture.
  49566. *
  49567. * @param {Texture} srcTexture - The source texture.
  49568. * @param {Texture} dstTexture - The destination texture.
  49569. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  49570. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  49571. * @param {number} [srcLevel=0] - The mipmap level to copy.
  49572. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  49573. */
  49574. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  49575. let dstX = 0;
  49576. let dstY = 0;
  49577. let dstZ = 0;
  49578. let srcX = 0;
  49579. let srcY = 0;
  49580. let srcZ = 0;
  49581. let srcWidth = srcTexture.image.width;
  49582. let srcHeight = srcTexture.image.height;
  49583. let srcDepth = 1;
  49584. if ( srcRegion !== null ) {
  49585. if ( srcRegion.isBox3 === true ) {
  49586. srcX = srcRegion.min.x;
  49587. srcY = srcRegion.min.y;
  49588. srcZ = srcRegion.min.z;
  49589. srcWidth = srcRegion.max.x - srcRegion.min.x;
  49590. srcHeight = srcRegion.max.y - srcRegion.min.y;
  49591. srcDepth = srcRegion.max.z - srcRegion.min.z;
  49592. } else {
  49593. // Assume it's a Box2
  49594. srcX = srcRegion.min.x;
  49595. srcY = srcRegion.min.y;
  49596. srcWidth = srcRegion.max.x - srcRegion.min.x;
  49597. srcHeight = srcRegion.max.y - srcRegion.min.y;
  49598. srcDepth = 1;
  49599. }
  49600. }
  49601. if ( dstPosition !== null ) {
  49602. dstX = dstPosition.x;
  49603. dstY = dstPosition.y;
  49604. dstZ = dstPosition.z || 0;
  49605. }
  49606. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  49607. const sourceGPU = this.get( srcTexture ).texture;
  49608. const destinationGPU = this.get( dstTexture ).texture;
  49609. encoder.copyTextureToTexture(
  49610. {
  49611. texture: sourceGPU,
  49612. mipLevel: srcLevel,
  49613. origin: { x: srcX, y: srcY, z: srcZ }
  49614. },
  49615. {
  49616. texture: destinationGPU,
  49617. mipLevel: dstLevel,
  49618. origin: { x: dstX, y: dstY, z: dstZ }
  49619. },
  49620. [
  49621. srcWidth,
  49622. srcHeight,
  49623. srcDepth
  49624. ]
  49625. );
  49626. this.device.queue.submit( [ encoder.finish() ] );
  49627. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  49628. this.textureUtils.generateMipmaps( dstTexture );
  49629. }
  49630. }
  49631. /**
  49632. * Copies the current bound framebuffer to the given texture.
  49633. *
  49634. * @param {Texture} texture - The destination texture.
  49635. * @param {RenderContext} renderContext - The render context.
  49636. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  49637. */
  49638. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  49639. const renderContextData = this.get( renderContext );
  49640. let sourceGPU = null;
  49641. if ( renderContext.renderTarget ) {
  49642. if ( texture.isDepthTexture ) {
  49643. sourceGPU = this.get( renderContext.depthTexture ).texture;
  49644. } else {
  49645. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  49646. }
  49647. } else {
  49648. if ( texture.isDepthTexture ) {
  49649. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  49650. } else {
  49651. sourceGPU = this.context.getCurrentTexture();
  49652. }
  49653. }
  49654. const destinationGPU = this.get( texture ).texture;
  49655. if ( sourceGPU.format !== destinationGPU.format ) {
  49656. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  49657. return;
  49658. }
  49659. let encoder;
  49660. if ( renderContextData.currentPass ) {
  49661. renderContextData.currentPass.end();
  49662. encoder = renderContextData.encoder;
  49663. } else {
  49664. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  49665. }
  49666. encoder.copyTextureToTexture(
  49667. {
  49668. texture: sourceGPU,
  49669. origin: [ rectangle.x, rectangle.y, 0 ],
  49670. },
  49671. {
  49672. texture: destinationGPU
  49673. },
  49674. [
  49675. rectangle.z,
  49676. rectangle.w
  49677. ]
  49678. );
  49679. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  49680. if ( renderContextData.currentPass ) {
  49681. const { descriptor } = renderContextData;
  49682. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  49683. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  49684. }
  49685. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  49686. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  49687. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  49688. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  49689. if ( renderContext.viewport ) {
  49690. this.updateViewport( renderContext );
  49691. }
  49692. if ( renderContext.scissor ) {
  49693. const { x, y, width, height } = renderContext.scissorValue;
  49694. renderContextData.currentPass.setScissorRect( x, y, width, height );
  49695. }
  49696. } else {
  49697. this.device.queue.submit( [ encoder.finish() ] );
  49698. }
  49699. }
  49700. }
  49701. /**
  49702. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  49703. *
  49704. * @augments SpotLight
  49705. */
  49706. class IESSpotLight extends SpotLight {
  49707. /**
  49708. * Constructs a new IES spot light.
  49709. *
  49710. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  49711. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  49712. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  49713. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  49714. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  49715. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  49716. */
  49717. constructor( color, intensity, distance, angle, penumbra, decay ) {
  49718. super( color, intensity, distance, angle, penumbra, decay );
  49719. /**
  49720. * TODO
  49721. *
  49722. * @type {?Texture}
  49723. * @default null
  49724. */
  49725. this.iesMap = null;
  49726. }
  49727. copy( source, recursive ) {
  49728. super.copy( source, recursive );
  49729. this.iesMap = source.iesMap;
  49730. return this;
  49731. }
  49732. }
  49733. /**
  49734. * This version of a node library represents the standard version
  49735. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  49736. * techniques and materials to node-based implementations.
  49737. *
  49738. * @private
  49739. * @augments NodeLibrary
  49740. */
  49741. class StandardNodeLibrary extends NodeLibrary {
  49742. /**
  49743. * Constructs a new standard node library.
  49744. */
  49745. constructor() {
  49746. super();
  49747. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  49748. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  49749. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  49750. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  49751. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  49752. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  49753. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  49754. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  49755. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  49756. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  49757. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  49758. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  49759. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  49760. this.addLight( PointLightNode, PointLight );
  49761. this.addLight( DirectionalLightNode, DirectionalLight );
  49762. this.addLight( RectAreaLightNode, RectAreaLight );
  49763. this.addLight( SpotLightNode, SpotLight );
  49764. this.addLight( AmbientLightNode, AmbientLight );
  49765. this.addLight( HemisphereLightNode, HemisphereLight );
  49766. this.addLight( LightProbeNode, LightProbe );
  49767. this.addLight( IESSpotLightNode, IESSpotLight );
  49768. this.addToneMapping( linearToneMapping, LinearToneMapping );
  49769. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  49770. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  49771. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  49772. this.addToneMapping( agxToneMapping, AgXToneMapping );
  49773. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  49774. }
  49775. }
  49776. /*
  49777. const debugHandler = {
  49778. get: function ( target, name ) {
  49779. // Add |update
  49780. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  49781. return target[ name ];
  49782. }
  49783. };
  49784. */
  49785. /**
  49786. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  49787. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  49788. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  49789. *
  49790. * @augments Renderer
  49791. */
  49792. class WebGPURenderer extends Renderer {
  49793. /**
  49794. * WebGPURenderer options.
  49795. *
  49796. * @typedef {Object} WebGPURenderer~Options
  49797. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49798. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49799. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49800. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49801. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49802. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  49803. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  49804. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  49805. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  49806. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  49807. */
  49808. /**
  49809. * Constructs a new WebGPU renderer.
  49810. *
  49811. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  49812. */
  49813. constructor( parameters = {} ) {
  49814. let BackendClass;
  49815. if ( parameters.forceWebGL ) {
  49816. BackendClass = WebGLBackend;
  49817. } else {
  49818. BackendClass = WebGPUBackend;
  49819. parameters.getFallback = () => {
  49820. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  49821. return new WebGLBackend( parameters );
  49822. };
  49823. }
  49824. const backend = new BackendClass( parameters );
  49825. //super( new Proxy( backend, debugHandler ) );
  49826. super( backend, parameters );
  49827. /**
  49828. * The generic default value is overwritten with the
  49829. * standard node library for type mapping.
  49830. *
  49831. * @type {StandardNodeLibrary}
  49832. */
  49833. this.library = new StandardNodeLibrary();
  49834. /**
  49835. * This flag can be used for type testing.
  49836. *
  49837. * @type {boolean}
  49838. * @readonly
  49839. * @default true
  49840. */
  49841. this.isWebGPURenderer = true;
  49842. }
  49843. }
  49844. /**
  49845. * A specialized group which enables applications access to the
  49846. * Render Bundle API of WebGPU. The group with all its descendant nodes
  49847. * are considered as one render bundle and processed as such by
  49848. * the renderer.
  49849. *
  49850. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  49851. * With a WebGL backend, the group can technically be rendered but without
  49852. * any performance improvements.
  49853. *
  49854. * @augments Group
  49855. */
  49856. class BundleGroup extends Group {
  49857. /**
  49858. * Constructs a new bundle group.
  49859. */
  49860. constructor() {
  49861. super();
  49862. /**
  49863. * This flag can be used for type testing.
  49864. *
  49865. * @type {boolean}
  49866. * @readonly
  49867. * @default true
  49868. */
  49869. this.isBundleGroup = true;
  49870. /**
  49871. * This property is only relevant for detecting types
  49872. * during serialization/deserialization. It should always
  49873. * match the class name.
  49874. *
  49875. * @type {string}
  49876. * @readonly
  49877. * @default 'BundleGroup'
  49878. */
  49879. this.type = 'BundleGroup';
  49880. /**
  49881. * Whether the bundle is static or not. When set to `true`, the structure
  49882. * is assumed to be static and does not change. E.g. no new objects are
  49883. * added to the group
  49884. *
  49885. * If a change is required, an update can still be forced by setting the
  49886. * `needsUpdate` flag to `true`.
  49887. *
  49888. * @type {boolean}
  49889. * @default true
  49890. */
  49891. this.static = true;
  49892. /**
  49893. * The bundle group's version.
  49894. *
  49895. * @type {number}
  49896. * @readonly
  49897. * @default 0
  49898. */
  49899. this.version = 0;
  49900. }
  49901. /**
  49902. * Set this property to `true` when the bundle group has changed.
  49903. *
  49904. * @type {boolean}
  49905. * @default false
  49906. * @param {boolean} value
  49907. */
  49908. set needsUpdate( value ) {
  49909. if ( value === true ) this.version ++;
  49910. }
  49911. }
  49912. /**
  49913. * This module is responsible to manage the post processing setups in apps.
  49914. * You usually create a single instance of this class and use it to define
  49915. * the output of your post processing effect chain.
  49916. * ```js
  49917. * const postProcessing = new PostProcessing( renderer );
  49918. *
  49919. * const scenePass = pass( scene, camera );
  49920. *
  49921. * postProcessing.outputNode = scenePass;
  49922. * ```
  49923. *
  49924. * Note: This module can only be used with `WebGPURenderer`.
  49925. */
  49926. class PostProcessing {
  49927. /**
  49928. * Constructs a new post processing management module.
  49929. *
  49930. * @param {Renderer} renderer - A reference to the renderer.
  49931. * @param {Node<vec4>} outputNode - An optional output node.
  49932. */
  49933. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  49934. /**
  49935. * A reference to the renderer.
  49936. *
  49937. * @type {Renderer}
  49938. */
  49939. this.renderer = renderer;
  49940. /**
  49941. * A node which defines the final output of the post
  49942. * processing. This is usually the last node in a chain
  49943. * of effect nodes.
  49944. *
  49945. * @type {Node<vec4>}
  49946. */
  49947. this.outputNode = outputNode;
  49948. /**
  49949. * Whether the default output tone mapping and color
  49950. * space transformation should be enabled or not.
  49951. *
  49952. * It is enabled by default by it must be disabled when
  49953. * effects must be executed after tone mapping and color
  49954. * space conversion. A typical example is FXAA which
  49955. * requires sRGB input.
  49956. *
  49957. * When set to `false`, the app must control the output
  49958. * transformation with `RenderOutputNode`.
  49959. *
  49960. * ```js
  49961. * const outputPass = renderOutput( scenePass );
  49962. * ```
  49963. *
  49964. * @type {boolean}
  49965. */
  49966. this.outputColorTransform = true;
  49967. /**
  49968. * Must be set to `true` when the output node changes.
  49969. *
  49970. * @type {Node<vec4>}
  49971. */
  49972. this.needsUpdate = true;
  49973. const material = new NodeMaterial();
  49974. material.name = 'PostProcessing';
  49975. /**
  49976. * The full screen quad that is used to render
  49977. * the effects.
  49978. *
  49979. * @private
  49980. * @type {QuadMesh}
  49981. */
  49982. this._quadMesh = new QuadMesh( material );
  49983. }
  49984. /**
  49985. * When `PostProcessing` is used to apply post processing effects,
  49986. * the application must use this version of `render()` inside
  49987. * its animation loop (not the one from the renderer).
  49988. */
  49989. render() {
  49990. this._update();
  49991. const renderer = this.renderer;
  49992. const toneMapping = renderer.toneMapping;
  49993. const outputColorSpace = renderer.outputColorSpace;
  49994. renderer.toneMapping = NoToneMapping;
  49995. renderer.outputColorSpace = LinearSRGBColorSpace;
  49996. //
  49997. const currentXR = renderer.xr.enabled;
  49998. renderer.xr.enabled = false;
  49999. this._quadMesh.render( renderer );
  50000. renderer.xr.enabled = currentXR;
  50001. //
  50002. renderer.toneMapping = toneMapping;
  50003. renderer.outputColorSpace = outputColorSpace;
  50004. }
  50005. /**
  50006. * Frees internal resources.
  50007. */
  50008. dispose() {
  50009. this._quadMesh.material.dispose();
  50010. }
  50011. /**
  50012. * Updates the state of the module.
  50013. *
  50014. * @private
  50015. */
  50016. _update() {
  50017. if ( this.needsUpdate === true ) {
  50018. const renderer = this.renderer;
  50019. const toneMapping = renderer.toneMapping;
  50020. const outputColorSpace = renderer.outputColorSpace;
  50021. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  50022. this._quadMesh.material.needsUpdate = true;
  50023. this.needsUpdate = false;
  50024. }
  50025. }
  50026. /**
  50027. * When `PostProcessing` is used to apply post processing effects,
  50028. * the application must use this version of `renderAsync()` inside
  50029. * its animation loop (not the one from the renderer).
  50030. *
  50031. * @async
  50032. * @return {Promise} A Promise that resolves when the render has been finished.
  50033. */
  50034. async renderAsync() {
  50035. this._update();
  50036. const renderer = this.renderer;
  50037. const toneMapping = renderer.toneMapping;
  50038. const outputColorSpace = renderer.outputColorSpace;
  50039. renderer.toneMapping = NoToneMapping;
  50040. renderer.outputColorSpace = LinearSRGBColorSpace;
  50041. //
  50042. const currentXR = renderer.xr.enabled;
  50043. renderer.xr.enabled = false;
  50044. await this._quadMesh.renderAsync( renderer );
  50045. renderer.xr.enabled = currentXR;
  50046. //
  50047. renderer.toneMapping = toneMapping;
  50048. renderer.outputColorSpace = outputColorSpace;
  50049. }
  50050. }
  50051. /**
  50052. * This special type of texture is intended for compute shaders.
  50053. * It can be used to compute the data of a texture with a compute shader.
  50054. *
  50055. * Note: This type of texture can only be used with `WebGPURenderer`
  50056. * and a WebGPU backend.
  50057. *
  50058. * @augments Texture
  50059. */
  50060. class StorageTexture extends Texture {
  50061. /**
  50062. * Constructs a new storage texture.
  50063. *
  50064. * @param {number} [width=1] - The storage texture's width.
  50065. * @param {number} [height=1] - The storage texture's height.
  50066. */
  50067. constructor( width = 1, height = 1 ) {
  50068. super();
  50069. /**
  50070. * The image object which just represents the texture's dimension.
  50071. *
  50072. * @type {{width: number, height: number}}
  50073. */
  50074. this.image = { width, height };
  50075. /**
  50076. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  50077. *
  50078. * @type {number}
  50079. */
  50080. this.magFilter = LinearFilter;
  50081. /**
  50082. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  50083. *
  50084. * @type {number}
  50085. */
  50086. this.minFilter = LinearFilter;
  50087. /**
  50088. * This flag can be used for type testing.
  50089. *
  50090. * @type {boolean}
  50091. * @readonly
  50092. * @default true
  50093. */
  50094. this.isStorageTexture = true;
  50095. }
  50096. }
  50097. /**
  50098. * This special type of buffer attribute is intended for compute shaders.
  50099. * It can be used to encode draw parameters for indirect draw calls.
  50100. *
  50101. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  50102. * and a WebGPU backend.
  50103. *
  50104. * @augments StorageBufferAttribute
  50105. */
  50106. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  50107. /**
  50108. * Constructs a new storage buffer attribute.
  50109. *
  50110. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  50111. * The subsequent parameter is then obsolete.
  50112. * @param {number} itemSize - The item size.
  50113. */
  50114. constructor( count, itemSize ) {
  50115. super( count, itemSize, Uint32Array );
  50116. /**
  50117. * This flag can be used for type testing.
  50118. *
  50119. * @type {boolean}
  50120. * @readonly
  50121. * @default true
  50122. */
  50123. this.isIndirectStorageBufferAttribute = true;
  50124. }
  50125. }
  50126. /**
  50127. * A loader for loading node objects in the three.js JSON Object/Scene format.
  50128. *
  50129. * @augments Loader
  50130. */
  50131. class NodeLoader extends Loader {
  50132. /**
  50133. * Constructs a new node loader.
  50134. *
  50135. * @param {LoadingManager} [manager] - A reference to a loading manager.
  50136. */
  50137. constructor( manager ) {
  50138. super( manager );
  50139. /**
  50140. * Represents a dictionary of textures.
  50141. *
  50142. * @type {Object<string,Texture>}
  50143. */
  50144. this.textures = {};
  50145. /**
  50146. * Represents a dictionary of node types.
  50147. *
  50148. * @type {Object<string,Node.constructor>}
  50149. */
  50150. this.nodes = {};
  50151. }
  50152. /**
  50153. * Loads the node definitions from the given URL.
  50154. *
  50155. * @param {string} url - The path/URL of the file to be loaded.
  50156. * @param {Function} onLoad - Will be called when load completes.
  50157. * @param {Function} onProgress - Will be called while load progresses.
  50158. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  50159. */
  50160. load( url, onLoad, onProgress, onError ) {
  50161. const loader = new FileLoader( this.manager );
  50162. loader.setPath( this.path );
  50163. loader.setRequestHeader( this.requestHeader );
  50164. loader.setWithCredentials( this.withCredentials );
  50165. loader.load( url, ( text ) => {
  50166. try {
  50167. onLoad( this.parse( JSON.parse( text ) ) );
  50168. } catch ( e ) {
  50169. if ( onError ) {
  50170. onError( e );
  50171. } else {
  50172. console.error( e );
  50173. }
  50174. this.manager.itemError( url );
  50175. }
  50176. }, onProgress, onError );
  50177. }
  50178. /**
  50179. * Parse the node dependencies for the loaded node.
  50180. *
  50181. * @param {Object} json - The JSON definition
  50182. * @return {Object<string,Node>} A dictionary with node dependencies.
  50183. */
  50184. parseNodes( json ) {
  50185. const nodes = {};
  50186. if ( json !== undefined ) {
  50187. for ( const nodeJSON of json ) {
  50188. const { uuid, type } = nodeJSON;
  50189. nodes[ uuid ] = this.createNodeFromType( type );
  50190. nodes[ uuid ].uuid = uuid;
  50191. }
  50192. const meta = { nodes, textures: this.textures };
  50193. for ( const nodeJSON of json ) {
  50194. nodeJSON.meta = meta;
  50195. const node = nodes[ nodeJSON.uuid ];
  50196. node.deserialize( nodeJSON );
  50197. delete nodeJSON.meta;
  50198. }
  50199. }
  50200. return nodes;
  50201. }
  50202. /**
  50203. * Parses the node from the given JSON.
  50204. *
  50205. * @param {Object} json - The JSON definition
  50206. * @return {Node} The parsed node.
  50207. */
  50208. parse( json ) {
  50209. const node = this.createNodeFromType( json.type );
  50210. node.uuid = json.uuid;
  50211. const nodes = this.parseNodes( json.nodes );
  50212. const meta = { nodes, textures: this.textures };
  50213. json.meta = meta;
  50214. node.deserialize( json );
  50215. delete json.meta;
  50216. return node;
  50217. }
  50218. /**
  50219. * Defines the dictionary of textures.
  50220. *
  50221. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  50222. * @return {NodeLoader} A reference to this loader.
  50223. */
  50224. setTextures( value ) {
  50225. this.textures = value;
  50226. return this;
  50227. }
  50228. /**
  50229. * Defines the dictionary of node types.
  50230. *
  50231. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  50232. * @return {NodeLoader} A reference to this loader.
  50233. */
  50234. setNodes( value ) {
  50235. this.nodes = value;
  50236. return this;
  50237. }
  50238. /**
  50239. * Creates a node object from the given type.
  50240. *
  50241. * @param {string} type - The node type.
  50242. * @return {Node} The created node instance.
  50243. */
  50244. createNodeFromType( type ) {
  50245. if ( this.nodes[ type ] === undefined ) {
  50246. console.error( 'THREE.NodeLoader: Node type not found:', type );
  50247. return float();
  50248. }
  50249. return nodeObject( new this.nodes[ type ]() );
  50250. }
  50251. }
  50252. /**
  50253. * A special type of material loader for loading node materials.
  50254. *
  50255. * @augments MaterialLoader
  50256. */
  50257. class NodeMaterialLoader extends MaterialLoader {
  50258. /**
  50259. * Constructs a new node material loader.
  50260. *
  50261. * @param {LoadingManager} [manager] - A reference to a loading manager.
  50262. */
  50263. constructor( manager ) {
  50264. super( manager );
  50265. /**
  50266. * Represents a dictionary of node types.
  50267. *
  50268. * @type {Object<string,Node.constructor>}
  50269. */
  50270. this.nodes = {};
  50271. /**
  50272. * Represents a dictionary of node material types.
  50273. *
  50274. * @type {Object<string,NodeMaterial.constructor>}
  50275. */
  50276. this.nodeMaterials = {};
  50277. }
  50278. /**
  50279. * Parses the node material from the given JSON.
  50280. *
  50281. * @param {Object} json - The JSON definition
  50282. * @return {NodeMaterial}. The parsed material.
  50283. */
  50284. parse( json ) {
  50285. const material = super.parse( json );
  50286. const nodes = this.nodes;
  50287. const inputNodes = json.inputNodes;
  50288. for ( const property in inputNodes ) {
  50289. const uuid = inputNodes[ property ];
  50290. material[ property ] = nodes[ uuid ];
  50291. }
  50292. return material;
  50293. }
  50294. /**
  50295. * Defines the dictionary of node types.
  50296. *
  50297. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  50298. * @return {NodeLoader} A reference to this loader.
  50299. */
  50300. setNodes( value ) {
  50301. this.nodes = value;
  50302. return this;
  50303. }
  50304. /**
  50305. * Defines the dictionary of node material types.
  50306. *
  50307. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  50308. * @return {NodeLoader} A reference to this loader.
  50309. */
  50310. setNodeMaterials( value ) {
  50311. this.nodeMaterials = value;
  50312. return this;
  50313. }
  50314. /**
  50315. * Creates a node material from the given type.
  50316. *
  50317. * @param {string} type - The node material type.
  50318. * @return {Node} The created node material instance.
  50319. */
  50320. createMaterialFromType( type ) {
  50321. const materialClass = this.nodeMaterials[ type ];
  50322. if ( materialClass !== undefined ) {
  50323. return new materialClass();
  50324. }
  50325. return super.createMaterialFromType( type );
  50326. }
  50327. }
  50328. /**
  50329. * A special type of object loader for loading 3D objects using
  50330. * node materials.
  50331. *
  50332. * @augments ObjectLoader
  50333. */
  50334. class NodeObjectLoader extends ObjectLoader {
  50335. /**
  50336. * Constructs a new node object loader.
  50337. *
  50338. * @param {LoadingManager} [manager] - A reference to a loading manager.
  50339. */
  50340. constructor( manager ) {
  50341. super( manager );
  50342. /**
  50343. * Represents a dictionary of node types.
  50344. *
  50345. * @type {Object<string,Node.constructor>}
  50346. */
  50347. this.nodes = {};
  50348. /**
  50349. * Represents a dictionary of node material types.
  50350. *
  50351. * @type {Object<string,NodeMaterial.constructor>}
  50352. */
  50353. this.nodeMaterials = {};
  50354. /**
  50355. * A reference to hold the `nodes` JSON property.
  50356. *
  50357. * @private
  50358. * @type {?Object}
  50359. */
  50360. this._nodesJSON = null;
  50361. }
  50362. /**
  50363. * Defines the dictionary of node types.
  50364. *
  50365. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  50366. * @return {NodeObjectLoader} A reference to this loader.
  50367. */
  50368. setNodes( value ) {
  50369. this.nodes = value;
  50370. return this;
  50371. }
  50372. /**
  50373. * Defines the dictionary of node material types.
  50374. *
  50375. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  50376. * @return {NodeObjectLoader} A reference to this loader.
  50377. */
  50378. setNodeMaterials( value ) {
  50379. this.nodeMaterials = value;
  50380. return this;
  50381. }
  50382. /**
  50383. * Parses the node objects from the given JSON.
  50384. *
  50385. * @param {Object} json - The JSON definition
  50386. * @param {Function} onLoad - The onLoad callback function.
  50387. * @return {Object3D}. The parsed 3D object.
  50388. */
  50389. parse( json, onLoad ) {
  50390. this._nodesJSON = json.nodes;
  50391. const data = super.parse( json, onLoad );
  50392. this._nodesJSON = null; // dispose
  50393. return data;
  50394. }
  50395. /**
  50396. * Parses the node objects from the given JSON and textures.
  50397. *
  50398. * @param {Object} json - The JSON definition
  50399. * @param {Object<string,Texture>} textures - The texture library.
  50400. * @return {Object<string,Node>}. The parsed nodes.
  50401. */
  50402. parseNodes( json, textures ) {
  50403. if ( json !== undefined ) {
  50404. const loader = new NodeLoader();
  50405. loader.setNodes( this.nodes );
  50406. loader.setTextures( textures );
  50407. return loader.parseNodes( json );
  50408. }
  50409. return {};
  50410. }
  50411. /**
  50412. * Parses the node objects from the given JSON and textures.
  50413. *
  50414. * @param {Object} json - The JSON definition
  50415. * @param {Object<string,Texture>} textures - The texture library.
  50416. * @return {Object<string,NodeMaterial>}. The parsed materials.
  50417. */
  50418. parseMaterials( json, textures ) {
  50419. const materials = {};
  50420. if ( json !== undefined ) {
  50421. const nodes = this.parseNodes( this._nodesJSON, textures );
  50422. const loader = new NodeMaterialLoader();
  50423. loader.setTextures( textures );
  50424. loader.setNodes( nodes );
  50425. loader.setNodeMaterials( this.nodeMaterials );
  50426. for ( let i = 0, l = json.length; i < l; i ++ ) {
  50427. const data = json[ i ];
  50428. materials[ data.uuid ] = loader.parse( data );
  50429. }
  50430. }
  50431. return materials;
  50432. }
  50433. }
  50434. /**
  50435. * In earlier three.js versions, clipping was defined globally
  50436. * on the renderer or on material level. This special version of
  50437. * `THREE.Group` allows to encode the clipping state into the scene
  50438. * graph. Meaning if you create an instance of this group, all
  50439. * descendant 3D objects will be affected by the respective clipping
  50440. * planes.
  50441. *
  50442. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  50443. *
  50444. * @augments Group
  50445. */
  50446. class ClippingGroup extends Group {
  50447. /**
  50448. * Constructs a new clipping group.
  50449. */
  50450. constructor() {
  50451. super();
  50452. /**
  50453. * This flag can be used for type testing.
  50454. *
  50455. * @type {boolean}
  50456. * @readonly
  50457. * @default true
  50458. */
  50459. this.isClippingGroup = true;
  50460. /**
  50461. * An array with clipping planes.
  50462. *
  50463. * @type {Array<Plane>}
  50464. */
  50465. this.clippingPlanes = [];
  50466. /**
  50467. * Whether clipping should be enabled or not.
  50468. *
  50469. * @type {boolean}
  50470. * @default true
  50471. */
  50472. this.enabled = true;
  50473. /**
  50474. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  50475. *
  50476. * @type {boolean}
  50477. * @default false
  50478. */
  50479. this.clipIntersection = false;
  50480. /**
  50481. * Whether shadows should be clipped or not.
  50482. *
  50483. * @type {boolean}
  50484. * @default false
  50485. */
  50486. this.clipShadows = false;
  50487. }
  50488. }
  50489. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, 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, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号